Sei sulla pagina 1di 103

Java Math Abs() Round() Ceil() Floor() Min()

Methods with Example


Java has had several advanced usage application including working with complex
calculations in physics, architecture/designing of structures, working with Maps and
corresponding latitudes/longitudes, etc.

In this tutorial, you will learn:

 Math.abs
 Math.round
 Math.ceil & Math.floor
 Math.min

All such applications require using complex calculations/equations that are tedious
to perform manually. Programmatically, such calculations would involve usage of
logarithms, trigonometry, exponential equations, etc.

Now, you cannot have all the log or trigonometry tables hard-coded somewhere in
your application or data. The data would be enormous and complex to maintain.

Java provides a very useful class for this purpose. It is the Math java class
(java.lang.Math).

This class provides methods for performing the operations like exponential,
logarithm, roots and trigonometric equations too.

Let us have a look at the methods provided by the Java Math class.
The two most fundamental elements in Math are the 'e' (base of the natural
logarithm) and 'pi' (ratio of the circumference of a circle to its diameter). These two
constants are often required in the above calculations/operations.

Hence the Math class java provides these two constants as double fields.

Math.E - having a value as 2.718281828459045

Math.PI - having a value as 3.141592653589793

A) Let us have a look at the table below that shows us the Basic methods and its
description

Method Description Arguments

abs Returns the absolute value of the argument Double, float, int, long

round Returns the closed int or long (as per the argument) double or float

ceil Returns the smallest integer that is greater than or equal to the argument Double

floor Returns the largest integer that is less than or equal to the argument Double

min Returns the smallest of the two arguments Double, float, int, long

max Returns the largest of the two arguments Double, float, int, long

Below is the code implementation of the above methods:

Note: There is no need to explicitly import java.lang.Math as its imported implicitly.


All its methods are static.

Integer Variable

int i1 = 27;
int i2 = -45;
Double(decimal) variables

double d1 = 84.6;
double d2 = 0.45;

Math.abs
public class Guru99 {
public static void main(String args[]) {

int i1 = 27;
int i2 = -45;
double d1 = 84.6;
double d2 = 0.45;
System.out.println("Absolute value of i1: " + Math.abs(i1));

System.out.println("Absolute value of i2: " + Math.abs(i2));

System.out.println("Absolute value of d1: " + Math.abs(d1));

System.out.println("Absolute value of d2: " + Math.abs(d2));

}
}
Output:
Absolute value of i1: 27
Absolute value of i2: 45
Absolute value of d1: 84.6
Absolute value of d2: 0.45

Math.round
public class Guru99 {
public static void main(String args[]) {
double d1 = 84.6;
double d2 = 0.45;
System.out.println("Round off for d1: " + Math.round(d1));

System.out.println("Round off for d2: " + Math.round(d2));


}
}
Output:
Round off for d1: 85
Round off for d2: 0

Math.ceil & Math.floor


public class Guru99 {
public static void main(String args[]) {
double d1 = 84.6;
double d2 = 0.45;
System.out.println("Ceiling of '" + d1 + "' = " + Math.ceil(d1));

System.out.println("Floor of '" + d1 + "' = " + Math.floor(d1));

System.out.println("Ceiling of '" + d2 + "' = " + Math.ceil(d2));

System.out.println("Floor of '" + d2 + "' = " + Math.floor(d2));

}
}
Output:
Ceiling of '84.6' = 85.0
Floor of '84.6' = 84.0
Ceiling of '0.45' = 1.0
Floor of '0.45' = 0.0

Math.min
public class Guru99 {
public static void main(String args[]) {
int i1 = 27;
int i2 = -45;
double d1 = 84.6;
double d2 = 0.45;
System.out.println("Minimum out of '" + i1 + "' and '" + i2 + "' = " + Math.min(i1,
i2));

System.out.println("Maximum out of '" + i1 + "' and '" + i2 + "' = " + Math.max(i1,


i2));

System.out.println("Minimum out of '" + d1 + "' and '" + d2 + "' = " + Math.min(d1,


d2));
System.out.println("Maximum out of '" + d1 + "' and '" + d2 + "' = " + Math.max(d1,
d2));

}
}
Output:
Minimum out of '27' and '-45' = -45
Maximum out of '27' and '-45' = 27
Minimum out of '84.6' and '0.45' = 0.45
Maximum out of '84.6' and '0.45' = 84.6

Method Description Arguments

exp Returns the base of natural log (e) to the power of argument Double

Log Returns the natural log of the argument double

Pow Takes 2 arguments as input and returns the value of the first argument Double
raised to the power of the second argument

floor Returns the largest integer that is less than or equal to the argument Double

Sqrt Returns the square root of the argument Double

B) Let us have a look at the table below that shows us the Exponential and
Logarithmic methods and its description-

Below is the code implementation of the above methods: (The same variables are
used as above)

public class Guru99 {


public static void main(String args[]) {
double d1 = 84.6;
double d2 = 0.45;
System.out.println("exp(" + d2 + ") = " + Math.exp(d2));
System.out.println("log(" + d2 + ") = " + Math.log(d2));

System.out.println("pow(5, 3) = " + Math.pow(5.0, 3.0));

System.out.println("sqrt(16) = " + Math.sqrt(16));

}
}
Output:
exp(0.45) = 1.568312185490169
log(0.45) = -0.7985076962177716
pow(5, 3) = 125.0
sqrt(16) = 4.0

C) Let us have a look at the table below that shows us the Trigonometric
methods and its description-

Method Description Arguments

Sin Returns the Sine of the specified argument Double

Cos Returns the Cosine of the specified argument double

Tan Returns the Tangent of the specified argument Double

Atan2 Converts rectangular coordinates (x, y) to polar(r, theta) and returns Double
theta

toDegrees Converts the arguments to degrees Double

Sqrt Returns the square root of the argument Double

toRadians Converts the arguments to radians Double

Default Arguments are in Radians


Below is the code implementation:

public class Guru99 {


public static void main(String args[]) {
double angle_30 = 30.0;
double radian_30 = Math.toRadians(angle_30);

System.out.println("sin(30) = " + Math.sin(radian_30));

System.out.println("cos(30) = " + Math.cos(radian_30));

System.out.println("tan(30) = " + Math.tan(radian_30));

System.out.println("Theta = " + Math.atan2(4, 2));

}
}
Output:
sin(30) = 0.49999999999999994
cos(30) = 0.8660254037844387
tan(30) = 0.5773502691896257
Theta = 1.1071487177940904

Now, with the above, you can also design your own scientific calculator in java.

How to easily Generate Random Numbers in


Java
In this tutorial, we Generate Random Number using Java Random class and
Math.Random methods.

 Generating Random Number Using Java


 Example: Using Java Random Class
 Example: Using Java Math.Random

Generating Random Number Using Java


Well, Java does provide some interesting ways to generate java random numbers,
not only for gambling but also several other applications especially related to
gaming, security, maths etc.
Let's see how it's done!!There are basically two ways to do it-

 Using Randomclass (in package java.util).


 Using Math.random java class (however this will generate double in the range
of 0.0 to 1.0 and not integers).

Let's look at them one by one -

Example: Using Java Random Class


First, we will see the implementation using java.util.Random-Assume we need to
generate 10 random numbers between 0 to 100.

import java.util.Random;
public class RandomNumbers{
public static void main(String[] args) {
Random objGenerator = new Random();
for (int iCount = 0; iCount< 10; iCount++){
int randomNumber = objGenerator.nextInt(100);
System.out.println("Random No : " + randomNumber);
}
}
}

An object of Random class is initialized as objGenerator. The Random class has a


method as nextInt. This will provide a random number based on the argument
specified as the upper limit, whereas it takes lower limit is 0.Thus, we get 10 random
numbers displayed.

Example: Using Java Math.Random


Now, if we want 10random numbers generated java but in the range of 0.0 to 1.0,
then we should make use of math.random()

You can use the following loop to generate them-

public class DemoRandom{


public static void main(String[] args) {
for(int xCount = 0; xCount< 10; xCount++){
System.out.println(Math.random());
}
}
}
Now, you know how those strange numbers are generated!!!

Java Date & Time: SimpleDateFormat, Current


Date & Compare
In this tutorial, you will learn -

 Display Current Date in Java


 SimpleDateFormat: Parse and Format Dates
 Compare Dates Example

Let us first understand the parameters that consist of a Date.

It will primarily contain -

 The year (in either 2 or 4 digits)


 The month (in either 2 digits, First 3 letters of the month or the entire word of
the month).
 The date (it will be the actual date of the month).
 The day (the day at the given date – like Sun, Mon, Tue, etc.)

Concerning computer systems, there are quite a lot of parameters that can be used
to associate with a date. We shall see them in the later parts of this topic.

Display Date in Java


Now let us see how Java provide us the Date. First, we shall see how to get the
current date-

Java provides a Date class under the java.util package, The package provides
several methods to play around with the date.

You can use the Date object by invoking the constructor of Date class as follows:

import java.util.Date;
class Date_Ex1 {
public static void main(String args[]) {
// Instantiate a Date object by invoking its constructor
Date objDate = new Date();
// Display the Date & Time using toString()
System.out.println(objDate.toString());
}
}

Output:

Wed Nov 29 06:36:22 UTC 2017

In above example date shown in default format, If we want to show the date and
time in another format, first understand the Formatting of date.

SimpleDateFormat: Parse and Format Dates


You all must have learned the alphabets in your kindergarten ….

Let us now learn the ABC’s of the date format.

Letter Date or Time Component Examples

G Era designator AD

y Year 2018

M Month in year July or Jul or 07


w Week in year 27

W Week in month 2

D Day in year 189

d Day in month 10

F Day of week in month 2

E Day name in week Tuesday or Tue

u Day number of week (1 = Monday, ..., 7 = Sunday) 1

a Am/pm marker PM

H Hour in day (0-23) 0

k Hour in day (1-24) 24

K Hour in am/pm (0-11) 0

h Hour in am/pm (1-12) 12

m Minute in hour 30

s Second in minute 55

S Millisecond 978
z Time zone Pacific Standard Time; PST; GMT-08:00

Z Time zone -0800

X Time zone -08 or -0800 or -08:00

Don’t worry, you don’t need to remember all of these, they can be referred anytime
you need to format a particular date.

How to use the SimpleDateFormat?


Java provides a class called a SimpleDateFormat that allows you to format and
parse dates in the as per your requirements.

You can use the above characters to specify the format - For example:

1) Date format required: 2012.10.23 20:20:45 PST

The appropriate date format specified will be- yyyy.MM.dd HH:mm:ss zzz

2) Date format required:09:30:00 AM 23-May-2012

The appropriate date format specified will be-hh:mm:ss a dd-MMM-yyyy

Tip: Be careful with the letter capitalization. If you mistake M with m, you will
undesired results!

Let's learn this with a code example.

import java.text.SimpleDateFormat;
import java.util.Date;
class TestDates_Format {
public static void main(String args[]) {
Date objDate = new Date(); // Current System Date and time is assigned to objDate
System.out.println(objDate);
String strDateFormat = "hh:mm:ss a dd-MMM-yyyy"; //Date format is Specified
SimpleDateFormat objSDF = new SimpleDateFormat(strDateFormat); //Date format string
is passed as an argument to the Date format object
System.out.println(objSDF.format(objDate)); //Date formatting is applied to the cur
rent date
}
}

Output:

Wed Nov 29 06:31:41 UTC 2017


06:31:41 AM 29-Nov-2017

Compare Dates Example

The most useful method of comparing dates is by using the method – compareTo()

Let us take a look at the below code snippet-

import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Date;

class TestDates_Compare {
public static void main(String args[]) throws ParseException {

SimpleDateFormat objSDF = new SimpleDateFormat("dd-mm-yyyy");


Date dt_1 = objSDF.parse("20-08-1981");
Date dt_2 = objSDF.parse("12-10-2012");

System.out.println("Date1 : " + objSDF.format(dt_1));


System.out.println("Date2 : " + objSDF.format(dt_2));

if (dt_1.compareTo(dt_2) > 0) {
System.out.println("Date 1 occurs after Date 2");
} // compareTo method returns the value greater than 0 if this Date is after the Da
te argument.
else if (dt_1.compareTo(dt_2) < 0) {
System.out.println("Date 1 occurs before Date 2");
} // compareTo method returns the value less than 0 if this Date is before the Date
argument;
else if (dt_1.compareTo(dt_2) == 0) {
System.out.println("Both are same dates");
} // compareTo method returns the value 0 if the argument Date is equal to the seco
nd Date;
else {
System.out.println("You seem to be a time traveller !!");
}
}
}
Output:
Date1 : 20-08-1981
Date2 : 12-10-2012
Date 1 occurs before Date 2

Multithreading in Java Tutorial with Examples


Any application can have multiple processes (instances). Each of this process can
be assigned either as a single thread or multiple threads.

We will see in this tutorial how to perform multiple tasks at the same time and also
learn more about threads and synchronization between threads.

In this tutorial, we will learn-

 What is Single Thread


 What is Multithreading
 Thread Life Cycle in Java
 Java Thread Synchronization
 Java Multithreading Example
What is Single Thread?
A single thread is basically a lightweight and the smallest unit of processing. Java
uses threads by using a "Thread Class".

There are two types of thread – user thread and daemon thread (daemon threads
are used when we want to clean the application and are used in the background).

When an application first begins, user thread is created. Post that, we can create
many user threads and daemon threads.

Single Thread Example:

package demotest;

public class GuruThread


{
public static void main(String[] args) {
System.out.println("Single Thread");
}
}

Advantages of single thread:

 Reduces overhead in the application as single thread execute in the system


 Also, it reduces the maintenance cost of the application.

What is Multithreading?
Multithreading in java is a process of executing two or more threads simultaneously
to maximum utilization of CPU.

Multithreaded applications are where two or more threads run concurrently; hence it
is also known as Concurrency in Java. This multitasking is done, when multiple
processes share common resources like CPU, memory, etc.

Each thread runs parallel to each other. Threads don't allocate separate memory
area; hence it saves memory. Also, context switching between threads takes less
time.

Example of Multi thread:

package demotest;
public class GuruThread1 implements Runnable
{
public static void main(String[] args) {
Thread guruThread1 = new Thread("Guru1");
Thread guruThread2 = new Thread("Guru2");
guruThread1.start();
guruThread2.start();
System.out.println("Thread names are following:");
System.out.println(guruThread1.getName());
System.out.println(guruThread2.getName());
}
@Override
public void run() {
}

Advantages of multithread:

 The users are not blocked because threads are independent, and we can
perform multiple operations at times
 As such the threads are independent, the other threads won't get affected if
one thread meets an exception.

Thread Life Cycle in Java


The Lifecycle of a thread:
There are various stages of life cycle of thread as shown in above diagram:

1. New
2. Runnable
3. Running
4. Waiting
5. Dead

1. New: In this phase, the thread is created using class "Thread class".It
remains in this state till the program starts the thread. It is also known as
born thread.
2. Runnable: In this page, the instance of the thread is invoked with a start
method. The thread control is given to scheduler to finish the execution. It
depends on the scheduler, whether to run the thread.
3. Running: When the thread starts executing, then the state is changed to
"running" state. The scheduler selects one thread from the thread pool, and it
starts executing in the application.
4. Waiting: This is the state when a thread has to wait. As there multiple threads
are running in the application, there is a need for synchronization between
threads. Hence, one thread has to wait, till the other thread gets executed.
Therefore, this state is referred as waiting state.
5. Dead: This is the state when the thread is terminated. The thread is in
running state and as soon as it completed processing it is in "dead state".

Some of the commonly used methods for threads are:


Method Description

start() This method starts the execution of the thread and JVM calls the run()
method on the thread.

Sleep(int milliseconds) This method makes the thread sleep hence the thread's execution will
pause for milliseconds provided and after that, again the thread starts
executing. This help in synchronization of the threads.

getName() It returns the name of the thread.

setPriority(int newpriority) It changes the priority of the thread.

yield () It causes current thread on halt and other threads to execute.

Example: In this example we are going to create a thread and explore built-in
methods available for threads.

package demotest;
public class thread_example1 implements Runnable {
@Override
public void run() {
}
public static void main(String[] args) {
Thread guruthread1 = new Thread();
guruthread1.start();
try {
guruthread1.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
guruthread1.setPriority(1);
int gurupriority = guruthread1.getPriority();
System.out.println(gurupriority);
System.out.println("Thread Running");
}
}

Explanation of the code:

Code Line 2: We are creating a class "thread_Example1" which is implementing the


Runnable interface (it should be implemented by any class whose instances are
intended to be executed by the thread.)

Code Line 4: It overrides run method of the runnable interface as it is mandatory to


override that method

Code Line 6: Here we have defined the main method in which we will start the
execution of the thread.

Code Line 7: Here we are creating a new thread name as "guruthread1" by


instantiating a new class of thread.

Code Line 8: we will use "start" method of the thread using "guruthread1" instance.
Here the thread will start executing.

Code Line 10: Here we are using the "sleep" method of the thread using
"guruthread1" instance. Hence, the thread will sleep for 1000 milliseconds.

Code 9-14: Here we have put sleep method in try catch block as there is checked
exception which occurs i.e. Interrupted exception.

Code Line 15: Here we are setting the priority of the thread to 1 from whichever
priority it was

Code Line 16: Here we are getting the priority of the thread using getPriority()

Code Line 17: Here we are printing the value fetched from getPriority

Code Line 18: Here we are writing a text that thread is running.

When you execute the above code, you get the following output:

Output:
5 is the Thread priority, and Thread Running is the text which is the output of our
code.

Java Thread Synchronization


In multithreading, there is the asynchronous behavior of the programs. If one thread
is writing some data and another thread which is reading data at the same time,
might create inconsistency in the application.

When there is a need to access the shared resources by two or more threads, then
synchronization approach is utilized.

Java has provided synchronized methods to implement synchronized behavior.

In this approach, once the thread reaches inside the synchronized block, then no
other thread can call that method on the same object. All threads have to wait till that
thread finishes the synchronized block and comes out of that.

In this way, the synchronization helps in a multithreaded application. One thread has
to wait till other thread finishes its execution only then the other threads are allowed
for execution.

It can be written in the following form:

Synchronized(object)
{
//Block of statements to be synchronized
}

Java Multithreading Example


In this example, we will take two threads and fetch the names of the thread.

Example1:

GuruThread1.java
package demotest;

public class GuruThread1 implements Runnable{

/**
* @param args
*/
public static void main(String[] args) {
Thread guruThread1 = new Thread("Guru1");
Thread guruThread2 = new Thread("Guru2");
guruThread1.start();
guruThread2.start();
System.out.println("Thread names are following:");
System.out.println(guruThread1.getName());
System.out.println(guruThread2.getName());
}
@Override
public void run() {
}

Explanation of the code:

Code Line 3: We have taken a class "GuruThread1" which implements Runnable (it
should be implemented by any class whose instances are intended to be executed
by the thread.)

Code Line 8: This is the main method of the class

Code Line 9: Here we are instantiating the Thread class and creating an instance
named as "guruThread1" and creating a thread.

Code Line 10: Here we are instantiating the Thread class and creating an instance
named a "guruThread2" and creating a thread.

Code Line 11: We are starting the thread i.e. guruThread1.

Code Line 12: We are starting the thread i.e. guruThread2.

Code Line 13: Outputting the text as "Thread names are following:"

Code Line 14: Getting the name of thread 1 using method getName() of the thread
class.

Code Line 15: Getting the name of thread 2 using method getName() of the thread
class.

When you execute the above code, you get the following output:
Output:

Thread names are being outputted here as

 Guru1
 Guru2

Example 2:

In this example, we will learn about overriding methods run() and start() method of a
runnable interface and create two threads of that class and run them accordingly.

Also, we are taking two classes,

 One which will implement the runnable interface and


 Another one which will have the main method and execute accordingly.

package demotest;
public class GuruThread2 {

public static void main(String[] args) {


// TODO Auto-generated method stub
GuruThread3 threadguru1 = new GuruThread3("guru1");
threadguru1.start();
GuruThread3 threadguru2 = new GuruThread3("guru2");
threadguru2.start();
}
}
class GuruThread3 implements Runnable {
Thread guruthread;
private String guruname;
GuruThread3(String name) {
guruname = name;
}
@Override
public void run() {
System.out.println("Thread running" + guruname);
for (int i = 0; i < 4; i++) {
System.out.println(i);
System.out.println(guruname);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Thread has been interrupted");
}
}
}
public void start() {
System.out.println("Thread started");
if (guruthread == null) {
guruthread = new Thread(this, guruname);
guruthread.start();
}

}
}

Explanation of the code:

Code Line 2: Here we are taking a class "GuruThread2" which will have the main
method in it.

Code Line 4: Here we are taking a main method of the class.

Code Line 6-7: Here we are creating an instance of class GuruThread3 (which is
created in below lines of the code) as "threadguru1" and we are starting the thread.

Code Line 8-9: Here we are creating another instance of class GuruThread3 (which
is created in below lines of the code) as "threadguru2" and we are starting the
thread.

Code Line 11: Here we are creating a class "GuruThread3" which is implementing
the runnable interface (it should be implemented by any class whose instances are
intended to be executed by the thread.)

Code Line 13-14: we are taking two class variables from which one is of the type
thread class and other of the string class.
Code Line 15-18: we are overriding the GuruThread3 constructor, which takes one
argument as string type (which is threads name) that gets assigned to class variable
guruname and hence the name of the thread is stored.

Code Line 20: Here we are overriding the run() method of the runnable interface.

Code Line 21: We are outputting the thread name using println statement.

Code Line 22-31: Here we are using a for loop with counter initialized to 0, and it
should not be less than 4 (we can take any number hence here loop will run 4 times)
and incrementing the counter. We are printing the thread name and also making the
thread sleep for 1000 milliseconds within a try-catch block as sleep method raised
checked exception.

Code Line 33: Here we are overriding start method of the runnable interface.

Code Line 35: We are outputting the text "Thread started".

Code Line 36-40: Here we are taking an if condition to check whether class variable
guruthread has value in it or no. If its null then we are creating an instance using
thread class which takes the name as a parameter (value for which was assigned in
the constructor). After which the thread is started using start() method.

When you execute the above code you get the following output:
Output:

There are two threads hence, we get two times message "Thread started".

We get the names of the thread as we have outputted them.

It goes into for loop where we are printing the counter and thread name and counter
starts with 0.

The loop executes three times and in between the thread is slept for 1000
milliseconds.

Hence, first, we get guru1 then guru2 then again guru2 because the thread sleeps
here for 1000 milliseconds and then next guru1 and again guru1, thread sleeps for
1000 milliseconds, so we get guru2 and then guru1.

Summary:

In this tutorial, we saw multithreaded applications in Java and how to use single and
multi threads.
 In multithreading, users are not blocked as threads are independent and can
perform multiple operations at time
 Various stages of life cycle of the thread are,
o New
o Runnable
o Running
o Waiting
o Dead
 We also learned about synchronization between threads, which help the
application to run smoothly.
 Multithreading makes many more application tasks easier.

Java Swing Tutorial: Examples to create GUI


What is Swing?
Java Swing is a lightweight Graphical User Interface (GUI) toolkit that includes a rich
set of widgets. It includes package lets you make GUI components for your Java
applications, and It is platform independent.

The Swing library is built on top of the Java Abstract Widget Toolkit (AWT), an older,
platform dependent GUI toolkit. You can use the Java GUI components like button,
textbox, etc. from the library and do not have to create the components from scratch.

In this tutorial, you will learn-

 What is Swing?
 What is a container class?
 GUI Example
 Layout Manager
 BorderLayout
 FlowLayout
 GridBagLayout

Java Swing class Hierarchy Diagram


All components in swing are JComponent which can be added to container classes.

What is a container class?


Container classes are classes that can have other components on it. So for creating
a GUI, we need at least one container object. There are 3 types of containers.

1. Panel: It is a pure container and is not a window in itself. The sole purpose of
a Panel is to organize the components on to a window.
2. Frame: It is a fully functioning window with its title and icons.
3. Dialog: It can be thought of like a pop-up window that pops out when a
message has to be displayed. It is not a fully functioning window like the
Frame.

Java GUI Example


Example: To learn to design GUI in Java
Step 1) Copy the following code into an editor

import javax.swing.*;
class gui{
public static void main(String args[]){
JFrame frame = new JFrame("My First GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
JButton button = new JButton("Press");
frame.getContentPane().add(button); // Adds Button to content pane of frame
frame.setVisible(true);
}
}

Step 2) Save, Compile, and Run the code.


Step 3) Now let's Add a Button to our frame. Copy following code into an editor

import javax.swing.*;
class gui{
public static void main(String args[]){
JFrame frame = new JFrame("My First GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
JButton button1 = new JButton("Press");
frame.getContentPane().add(button1);
frame.setVisible(true);
}
}

Step 4) Execute the code. You will get a big button


Step 5) How about adding two buttons? Copy the following code into an editor.

import javax.swing.*;
class gui{
public static void main(String args[]){
JFrame frame = new JFrame("My First GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
JButton button1 = new JButton("Button 1");
JButton button2 = new JButton("Button 2");
frame.getContentPane().add(button1);
frame.getContentPane().add(button2);
frame.setVisible(true);
}
}

Step 6) Save , Compile , and Run the program.


Step 7) Unexpected output =? Buttons are getting overlapped.

Java Layout Manger


The Layout manager is used to layout (or arrange) the GUI java components inside
a container.There are many layout managers, but the most frequently used are-

Java BorderLayout

A BorderLayout places components in up to five areas: top, bottom, left, right, and
center. It is the default layout manager for every java JFrame

Java FlowLayout
is the default layout manager for every JPanel. It simply lays out
FlowLayout
components in a single row one after the other.

Java GridBagLayout
It is the more sophisticated of all layouts. It aligns components by placing them
within a grid of cells, allowing components to span more than one cell.

Step 8) How about creating a chat frame like below?


Try to code yourself before looking at the program below.

//Usually you will require both swing and awt packages


// even if you are working with just swings.
import javax.swing.*;
import java.awt.*;
class gui {
public static void main(String args[]) {

//Creating the Frame


JFrame frame = new JFrame("Chat Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);

//Creating the MenuBar and adding components


JMenuBar mb = new JMenuBar();
JMenu m1 = new JMenu("FILE");
JMenu m2 = new JMenu("Help");
mb.add(m1);
mb.add(m2);
JMenuItem m11 = new JMenuItem("Open");
JMenuItem m22 = new JMenuItem("Save as");
m1.add(m11);
m1.add(m22);

//Creating the panel at bottom and adding components


JPanel panel = new JPanel(); // the panel is not visible in output
JLabel label = new JLabel("Enter Text");
JTextField tf = new JTextField(10); // accepts upto 10 characters
JButton send = new JButton("Send");
JButton reset = new JButton("Reset");
panel.add(label); // Components Added using Flow Layout
panel.add(label); // Components Added using Flow Layout
panel.add(tf);
panel.add(send);
panel.add(reset);

// Text Area at the Center


JTextArea ta = new JTextArea();

//Adding Components to the frame.


frame.getContentPane().add(BorderLayout.SOUTH, panel);
frame.getContentPane().add(BorderLayout.NORTH, mb);
frame.getContentPane().add(BorderLayout.CENTER, ta);
frame.setVisible(true);
}
}

How to Split a String in Java: Learn with


Example
While programming, we may need to break a string based on some attributes.
Mostly this attribute will be a separator or a common - with which you want to break
or split the string.

The StrSplit() method splits a String into an array of substrings given a specific
delimiter.

Syntax
public String split(String regex)
public String split(String regex, int limit)
Parameter
 Regex: The regular expression is applied to the text/string
 Limit: A limit is a maximum number of values the array. If it is omitted or zero,
it will return all the strings matching a regex.

Split String Example


Suppose we have a string variable named strMain formed of a few words like Alpha,
Beta, Gamma, Delta, Sigma – all separated by the comma (,).

Here if we want all individual strings, the best possible pattern would be to split it
based on the comma. So we will get five separate strings as follows:

 Alpha
 Beta
 Gamma
 Delta
 Sigma

Use the split method against the string that needs to be divided and provide the
separator as an argument.

In this case, the separator is a comma (,) and the result of the split operation will
give you an array split.

class StrSplit{
public static void main(String []args){
String strMain = "Alpha, Beta, Delta, Gamma, Sigma";
String[] arrSplit = strMain.split(", ");
for (int i=0; i < arrSplit.length; i++)
{
System.out.println(arrSplit[i]);
}
}
}

The loop in the code just prints each string (element of array) after the split
operation, as shown below-

Output:

Alpha
Beta
Delta
Gamma
Sigma

Example: Java String split() method with regex and length


Consider a situation, wherein you require only the first ‘n’ elements after the split
operation but want the rest of the string to remain as it is. An output something like
this-

1. Alpha
2. Beta
3. Delta, Gamma, Sigma

This can be achieved by passing another argument along with the split operation,
and that will be the limit of strings required.

Consider the following code –

class StrSplit2{
public static void main(String []args){
String strMain = "Alpha, Beta, Delta, Gamma, Sigma";
String[] arrSplit_2 = strMain.split(", ", 3);
for (int i=0; i < arrSplit_2.length; i++){
System.out.println(arrSplit_2[i]);
}
}
}
Output:
Alpha
Beta
Delta, Gamma, Sigma
How to Split a String by Space
Consider a situation, wherein you want to split a string by space. Let’s consider an
example here; we have a string variable named strMain formed of a few
words Welcome to Guru99.

public class StrSplit3{


public static void main(String args[]){
String strMain ="Welcome to Guru99";
String[] arrSplit_3 = strMain.split("\\s");
for (int i=0; i < arrSplit_3.length; i++){
System.out.println(arrSplit_3[i]);
}
}
}

Output:

Welcome
to
Guru99

How to read file in Java: BufferedReader


Example
How to read a file in Java?
Java provides several mechanisms to read from File. The most useful package that
is provided for this is the java.io.Reader.This class contains the Class
BufferedReader under package java.io.BufferedReader

What is BufferedReader in Java?


BufferedReader is Java class to reads the text from an Input stream (like a file) by
buffering characters that seamlessly reads characters, arrays or lines.

In general, each read request made of a Reader causes a corresponding read


request to be made of the underlying character or byte stream.
It is therefore advisable to wrap a BufferedReader around any Reader whose read()
operations may be costly, such as java FileReaders and InputStreamReaders.

A typical usage would involve passing the file path to the BufferedReader as follows:

objReader = new BufferedReader(new FileReader("D:\DukesDiary.txt"));


//Assuming you have a text file in D drive

This basically loads your file in the objReader.Now, you will need to iterate through
the contents of the file and print it.

The while loop in the below code will read the file until it has reached the end of file

while ((strCurrentLine = objReader.readLine()) != null) {


System.out.println(strCurrentLine);
}

strCurrentLine reads the current line and objReader.readLine() returns a string.


Hence, the loop will iterate until it’s not null.

BufferedReader Example:
Below code shows the complete implementation.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFileExample {

public static void main(String[] args) {


BufferedReader objReader = null;
try {
String strCurrentLine;

objReader = new BufferedReader(new FileReader("D:\\DukesDiary.txt"));

while ((strCurrentLine = objReader.readLine()) != null) {

System.out.println(strCurrentLine);
}

} catch (IOException e) {
e.printStackTrace();

} finally {

try {
if (objReader != null)
objReader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}

Note:

The above code has some very important handlings especially in the finally block of
the code.

This code will ensure that the memory management is done efficiently and the
objReader.close() method is called that releases the memory.

BufferedReader JDK7 Example:


import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFileExample_jdk7 {

private static final String FILENAME = "D:\\DukesDiary.txt";

public static void main(String[] args) {

try (BufferedReader br = new BufferedReader(new FileReader(FILENAME))) {

String strCurrentLine;

while ((strCurrentLine = br.readLine()) != null) {


System.out.println(strCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Java Reflection API Tutorial with Example


What is Reflection in Java?
Java Reflection is the process of analyzing and modifying all the capabilities of a
class at runtime. Reflection API in Java is used to manipulate class and its members
which include fields, methods, constructor, etc. at runtime.

One advantage of reflection API in Java is, it can manipulate private members of the
class too.

The java.lang.reflect package provides many classes to implement reflection


java.Methods of the java.lang.Class class is used to gather the complete metadata
of a particular class.

In this tutorial, you will learn-

 What is Reflection
 Class in java.lang.reflect Package
 Methods used in java.lang.Class
 How to get complete information about a class
 Example 1: How to get Metadata of Class
 Example 2: How to get Metadata of Variable
 Example 3: How to get Metadata of Method
 Example 4: How to get Metadata of Constructors

Class in java.lang.reflect Package


Following is a list of various Java classes in java.lang.package to implement
reflection-

 Field: This class is used to gather declarative information such as datatype,


access modifier, name and value of a variable.
 Method: This class is used to gather declarative information such as access
modifier, return type, name, parameter types and exception type of a method.
 Constructor: This class is used to gather declarative information such as
access modifier, name and parameter types of a constructor.
 Modifier: This class is used to gather information about a particular access
modifier.

Methods used in java.lang.Class


 Public String getName (): Returns the name of the class.
 public Class getSuperclass(): Returns the super class reference
 Public Class[] getInterfaces() : Returns an array of interfaces implemented
by the specified class
 Public in getModifiers (): Returns an integer value representing the
modifiers of the specified class which needs to be passed as a parameter to
"public static String toString (int i )"method which returns the access
specifier for the given class.

How to get complete information about a class


To get information about variables, methods, and constructors of a class, we need to
create an object of the class.

public class Guru99ClassObjectCreation {


public static void main (String[] args) throws ClassNotFoundException {
//1 - By using Class.forname() method
Class c1 = Class.forName("Guru99ClassObjectCreation");
//2- By using getClass() method
Guru99ClassObjectCreation guru99Obj = new Guru99ClassObjectCreation(
);
Class c2 = guru99Obj.getClass();
//3- By using .class
Class c3= Guru99ClassObjectCreation.class;
}
}
 Following example shows different ways to create object of class "class" :

Example 1 : How to get Metadata of Class


Following example shows how to get metadata such as: Class name, super class
name, implemented interfaces, and access modifiers of a class.

We will get the metadata of below class named Guru99Base.class:

import java.io.Serializable;
public abstract class Guru99Base implements Serializable,Cloneable {
}

1. Name of the class is: Guru99Base


2. It's access modifiers are: public and abstract
3. It has implemented interfaces: Serializable and Cloneable
4. Since it has not extended any class explicitly, it's super class is:
java.lang.Object

Below class will get the meta data of Guru99Base.class and print it:
import java.lang.reflect.Modifier;
public class Guru99GetclassMetaData {

public static void main (String [] args) throws ClassNotFoundException {


// Create Class object for Guru99Base.class
Class guru99ClassObj = Guru99Base.class;
// Print name of the class
system.out.println("Name of the class is : " +guru99ClassObj.getName());

// Print Super class name


system.out.println("Name of the super class is : " +guru99ClassObj.getSuperc
lass().getName());

// Get the list of implemented interfaces in the form of Class array using g
etInterface() method
class[] guru99InterfaceList = guru99classObj.getInterfaces();

// Print the implemented interfaces using foreach loop


system.out.print("Implemented interfaces are : ");
for (Class guru99class1 : quru99 InterfaceList) {
system.out.print guru99class1.getName() + " ");
}
system.out.println();

//Get access modifiers using get Modifiers() method and toString() method of
java.lang.reflect.Modifier class
int guru99AccessModifier= guru99classObj.getModifiers();
// Print the access modifiers
System.Out.println("Access modifiers of the class are : " +Modifier.tostring
(guru99AccessModifier));

}
}

1. print the name of the class using getName method


2. Print the name of the super class using getSuperClass().getName() method
3. Print the name of the implemented interfaces
4. Print the access modifiers used by the class
Example 2 : How to get Metadata of Variable
Following examples shows how to get metadata of variable:

Here, we are creating a class named Guru99VariableMetaData .class with some


variables:

package guru;
public class Guru99VariableMetaData {
public static int guru99IntVar1=1111;
static int guru99IntVar2=2222;

static String guru99StringVar1="guru99.com";

static String guru99StringVar2="Learning Reflection API";


}
Steps to get the metadata about the variables in the above class:

1. Create the class object of the above class i.e. Guru99VariableMetaData.class


as below:
2. Guru99VariableMetaData guru99ClassVar = new Guru99VariableMetaData();
Class guru99ClassObjVar = guru99ClassVar.getClass();

3. Get the metadata in the form of field array


using getFields() or getDeclaredFields() methods as below:
4. Field[] guru99Field1= guru99ClassObjVar .getFields();
Field[] guru99Fiel2= guru99ClassObjVar .getDeclaredFields();

getFields() method returns metadata of the public variable from the specified class
as well as from its super class.

getDeclaredFields() method returns metadata of the all the variables from the
specified class only.

3. Get the name of the variables using "public String getName()" method.
4. Get the datatype of the variables using "public Class getType()" method.
5. Get the value of the variable using "public xxx get (Field)" method.

Here, xxx could be a byte or short of any type of value we want to fetch.

6. Get the access modifiers of the variables using getModifier() and


Modifier.toString(int i) methods.

Here, we are writing a class to get the metadata of the variables present
in the class Guru99VariableMetaData .class:
package guru;
import java.lang.reflect.Field;

public class Guru99VariableMetaDataTest {


public static void main(String[] args) throws IllegalArgumentException, Ille
galAccessException {
// Create Class object for Guru99VariableMetaData.class
Guru99VariableMetaData guru99ClassVar = new Guru99VariableMetaData();
Class guru99ClassObjVar = guru99ClassVar.getClass();
// Get the metadata of all the fields of the class Guru99VariableMetaData
Field[] guru99Field1= guru99ClassObjVar.getDeclaredFields();

// Print name, datatypes, access modifiers and values of the varibales of th


e specified class
for(Field field : guru99Field1) {
System.out.println("Variable name : "+field.getName());
System.out.println("Datatypes of the variable :"+field.getType());

int guru99AccessModifiers = field.getModifiers();


System.out.printlln("Access Modifiers of the variable : "+Modifier.toString(
guru99AccessModifiers));
System.out.println("Value of the variable : "+field.get(field));
System.out.println();
system.out.println("* * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * * *") ;
}
}
}

1. Created class object for Guru99VariableMetaData.class


2. Got all the metadata of the variables in a Field array
3. Printed all the variable names in the class
Guru99VariableMetaData.class
4. Printed all the data types of the variables in the class
Guru99VariableMetaData.class
5. Printed all the access modifiers of the variables in the class
Guru99VariableMetaData.class
6. Printed values of all the variables in Printed all the data types of the
variables in the class Guru99VariableMetaData.class
Example 3 : How to get Metadata of Method
Following examples shows how to get metadata of a method:

Here, we are creating a class named Guru99MethodMetaData .class with


some methods
package guru;
import java.sql.SQLException;
public class Guru99MethodMetaData {

public void guru99Add(int firstElement, int secondElement , String result)

throws ClassNotFoundException, ClassCastException{


System.out.println("Demo method for Reflextion API");

}
public String guru99Search(String searchString)
throws ArithmeticException, InterruptedException{
System.out.println("Demo method for Reflection API");

return null;
}
public void guru99Delete(String deleteString)

throws SQLException{
System.out.println("Demo method for Reflection API");

}
}

Steps to get the metadata about the methods in the above class :

7. Create the class object of the above class i.e.


Guru99MethodMetaData.class as below:
8. Guru99MethodMetaData guru99ClassVar = new Guru99MethodMetaData ();
Class guru99ClassObjVar = guru99ClassVar.getClass();

9. Get method information in a Method array using getMethods() and


getDeclaredMethods() method as below:
10. Method[] guru99 Method 1= guru99ClassObjVar .get Methods();
Method [] guru99 Method 2= guru99ClassObjVar .getDeclared Method s();
getMethods() method returns metadata of the public methods from the
specified class as well as from its super class.

getDeclaredMethods() method returns metadata of the all the


methods from the specified class only.

11. Get the name of the method using getName() method.


12. Get the return type of the method using getReturnType() method.
13. Get access modifiers of the methods
using getModifiers() and Modifiers.toString(int i) methods.
14. Get method parameter types using getParameterTypes() method
which returns a class array.
15. Get thrown exception using getExceptionTypes() method which
returns a class array.

Here, we are writing a class to get the metadata of the methods present
in the class Guru99MethodMetaData.class:
package guru;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public class Guru99MethodMetaDataTest {

public static void main (String[] args) {


// Create Class object for Guru99Method MetaData.class
class guru99ClassObj = Guru99MethodMetaData.class;

// Get the metadata or information of all the methods of the class u


sing getDeclaredMethods()
Method[] guru99Methods=guru99classObj.getDeclaredMethods();

for(Method method : guru99Methods) {


// Print the method names
System.out.println("Name of the method : "+method.getName());

// Print return type of the methods


System.out.println("Return type of the method : "+method.getReturnTy
pe());

//Get the access modifier list and print


int guru99ModifierList = method.getModifiers();
System.Out.printlin ("Method access modifiers : "+Modifier.toString(
guru99ModifierList));

// Get and print parameters of the methods


Class[] guru99ParamList= method.getParameterTypes();
system.out.print ("Method parameter types : ");
for (Class class1 : guru99ParamList){
System.out.println(class1.getName()+" ");
}
System.out.println();

// Get and print exception thrown by the method


Class[] guru99ExceptionList = method. getExceptionTypes();
system.out.print("Excpetion thrown by method :");
for (Class class1 : guru99ExceptionList) {
System.out.println (class1.getName() +" "):
}
System.Out.println();
system.out.println("* * * * * * * * * * * * * * * * * * * * * * * *
* * * * * * * ");

}
}

16. Created class object for Guru99MethodMetaData.class


17. Got all the metadata of all the methods in a Method array
18. Printed all the method names present in the class
Guru99MethodMetaData.class
19. Printed return types of the methods in the class
Guru99MethodMetaData.class
20. Printed all the access modifiers of the methods in the class
Guru99MethodMetaData.class
21. Printed parameter types of the methods in
Guru99MethodMetaData.class
22. Printed exceptions are thrown by methods in
Guru99MethodMetaData.class
Example 4 : How to get Metadata of Constructors
Following examples shows how to get metadata of constructors:

Here, we are creating a class named Guru99Constructor.class with different


constructors:
package guru;

import java.rmi.RemoteException;
import java.sql.SQLException;

public class Guru99Constructor {

public Guru99Constructor(int no) throws ClassCastException ,ArithmeticExcept


ion{ }
public Guru99Constructor(int no, String name) throws RemoteException ,SQLExc
eption{ }
public Guru99Constructor(int no, String name, String address) throws Interru
ptedException{ }
}

Here, we are writing a class to get the metadata of the constructors


present in the class Guru99Constructor.class:
package guru;
import java.lang.reflect.Constructor;
public class Guru99ConstructorMetaDataTest {

public static void main (String[] args) {


// Create Class object for Guru99Constructor.class
Class guru99Class=Guru99Constructor.class;

// Get all the constructor information in the Constructor array


Constructor[] guru99ConstructorList = guru99Class.getConstructors();

for (Constructor constructor : guru99ConstructorList) {


// Print all name of each constructor
System.out.println("Constrcutor name : "+constructor.getName
());

//Get and print access modifiers of each constructor


int guru99Modifiers= constructor.getModifiers();
System.Out.printlin ("Constrctor modifier : "+Modifier.toStr
ing(guru99Modifiers));

// Get and print parameter types


Class[] guru99ParamList=constructor.getParameterTypes();
System.out.print ("Constrctor parameter types :");
for (Class class1 : guru99ParamList) {
System.out.println(class1.getName() +" ");
}
System. out.println();

// Get and print exception thrown by constructors


Class[] guru99ExceptionList=constructor.getFxceptionTypes();
System.out.println("Exception thrown by constructors :");
for (Class class1 : guru99ExceptionList) {
System.out.println(class1.getName() +" ");
}
System.out.println();
System.out.println("****************************************
***");
}
}
}
23. Created class object for Guru99Constructor.class
24. Got all the metadata of all the constructors in a Constructor array
25. Printed all the constructor's names present in the class
Guru99Constructor.class
26. Printed all the access modifiers of the constructors in the class
Guru99Constructor.class
27. Printed parameter types of the constructors in Guru99Constructor.class
28. Printed exceptions are thrown by constructors in
Guru99Constructor.class
Summary:

o Reflection programming in java helps in retrieving and modifying


information about Classes and Class members such variable, methods,
constructors.
o Reflection API in Java can be implemented using classes in
java.lang.reflect package and methods of java.lang.Class class.
o Some commonly used methods of java.lang.Class class are getName
(), getSuperclass (), getInterfaces (), getModifiers () etc.
o Some commonly used classes in java.lang.reflect package are Field,
Method, Constructor, Modifier, etc.
o Reflection API can access private methods and variables of a class
which could be a security threat.
o Reflection API is a powerful capability provided by Java, but it comes
with some overheads such as slower performance, security
vulnerability, and permission issue. Hence, reflection API should be
treated as the last resort to performing an operation.

Java Program to Check Prime Number


What is a Prime Number?
A prime number is a number that is only divisible by 1 or itself. For example, 11 is
only divisible by 1 or itself. Other Prime numbers 2, 3, 5, 7, 11, 13, 17....

Note: 0 and 1 are not prime numbers. 2 is the only even prime number.

Java Program to check whether number is prime or not


Program Logic:

 We need to divide an input number, say 17 from values 2 to 17 and check the
remainder. If remainder is 0 number is not prime.
 No number is divisible by more than half of itself. So we need to loop through
just numberToCheck/2 . If input is 17, half is 8.5 and the loop will iterate through
values 2 to 8
 If a numberToCheck is completely divisible by other number, flag isPrime is
set to true and the loop is exited.

1. public class PrimenumberToCheckCheck {


2.
3. public static void main(String[] args) {
4. int remainder;
5. boolean isPrime=true;
6. int numberToCheck=17; // Enter the numberToCheckber you want to check for prime
7.
8. //Loop to check whether the numberToCheckber is divisible any numberToCheckber
other than 1 and iteself
9. for(int i=2;i<=numberToCheck/2;i++)
10. {
11. //numberToCheckber is dived by itself
12. remainder=numberToCheck%i;
13. System.out.println(numberToCheck+" Divided by "+ i + " gives a remain
der "+remainder);
14.
15. //if remainder is 0 than numberToCheckber is not prime and break loop. Ele
se continue loop
16. if(remainder==0)
17. {
18. isPrime=false;
19. break;
20. }
21. }
22. // Check value true or false,if isprime is true then numberToCheckber is prime
otherwise not prime
23. if(isPrime)
24. System.out.println(numberToCheck + " is a Prime numberToCheckber");
25. else
26. System.out.println(numberToCheck + " is not a Prime numberToCheckber");
27. }
28. }

Output:
17 Divided by 2 gives a remainder 1
17 Divided by 3 gives a remainder 2
17 Divided by 4 gives a remainder 1
17 Divided by 5 gives a remainder 2
17 Divided by 6 gives a remainder 5
17 Divided by 7 gives a remainder 3
17 Divided by 8 gives a remainder 1
17 is a Prime Number

Check our program to Find Prime Numbers from 1 to 100

Prime Number From 1 to 100 Program in Java


What is a Prime Number?
A prime number is a number that is only divisible by 1 or itself. For example, 11 is
only divisible by 1 or itself. Other Prime numbers 2, 3, 5, 7, 11, 13, 17....
Note: 0 and 1 are not prime numbers. 2 is the only even prime number.

Java Program to display prime numbers from 1 to 100


Program Logic:

 The main method contains a loop to check prime numbers one by one.
 The main method calls the method CheckPrime to determine whether a
number is prime
 We need to divide an input number, say 17 from values 2 to 17 and check the
remainder. If the remainder is 0 number is not prime.
 No number is divisible by more than half of itself. So, we need to loop through
just numberToCheck/2. If the input is 17, half is 8.5, and the loop will iterate
through values 2 to 8
 If numberToCheck is entirely divisible by another number, we return false, and
loop is broken.
 If numberToCheckis prime, we return true.
 In the main method, check isPrime is TRUE and add to primeNumbersFound
String
 Lastly, print the results
1. public class primeNumbersFoundber {
2.
3. public static void main(String[] args) {
4.
5. int i;
6. int num = 0;
7. int maxCheck = 100; // maxCheck limit till which you want to find p
rime numbers
8. boolean isPrime = true;
9.
10. //Empty String
11. String primeNumbersFound = "";
12.
13. //Start loop 1 to maxCheck
14. for (i = 1; i <= maxCheck; i++) {
15. isPrime = CheckPrime(i);
16. if (isPrime) {
17. primeNumbersFound = primeNumbersFound + i + " ";
18. }
19. }
20. System.out.println("Prime numbers from 1 to " + maxCheck + " are:")
;
21. // Print prime numbers from 1 to maxCheck
22. System.out.println(primeNumbersFound);
23. }
24. public static boolean CheckPrime(int numberToCheck) {
25. int remainder;
26. for (int i = 2; i <= numberToCheck / 2; i++) {
27. remainder = numberToCheck % i;
28. //if remainder is 0 than numberToCheckber is not prime and brea
k loop. Elese continue loop
29. if (remainder == 0) {
30. return false;
31. }
32. }
33. return true;
34.
35. }
36.
37. }

Output:
Prime numbers from 1 to 100 are:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

Check our program to Find Prime Numbers from Any Input Number

How to Convert Char to String & String to char


in Java
In this tutorial, we will study programs to

1. To convert a character to String


2. To convert a String to character

Convert Char To String


There are multiple ways to convert a Char to String in Java. In fact, String is made of
Character array in Java. Char is 16 bit or 2 bytes unsigned data type.

We can convert String to Character using 2 methods -

1. Method 1: Using toString() method


2. Method 2: Using valueOf() method

1. //Convert character to String using string method


2. package com.guru99;
3.
4. public class CharToString {
5.
6. public static void main(String[] args)
7. {
8.
9. //input character variable
10. char myChar = 'g';
11.
12. //Using toString() method
13. //toString method take character parameter and convert string.
14. String myStr = Character.toString(myChar);
15.
16. //print string value
17. System.out.println("String is: "+myStr);
18.
19.
20. //we can use other method for valueOf()
21.
22.
23. //valueOf method take character parameter and convert string.
24. myStr = String.valueOf(myChar);
25. ////print string value
26. System.out.println("String is: "+myStr);
27.
28. }
29.
30. }

Output :
String is: g
String is: g

Convert String to char


We can convert a String to char using charAt() method of String class.

1. //Convert String to Character using string method


2. package com.guru99;
3.
4. public class StringToChar {
5.
6. public static void main(String[] args)
7. {
8. //input String
9. String myStr = "Guru99";
10.
11. //find string length using length method.
12. int stringLength =myStr.length();
13.
14. //for loop start 0 to total length
15. for(int i=0; i < stringLength;i++)
16. {
17. //chatAt method find Position and convert to character.
18. char myChar = myStr.charAt(i);
19.
20. //print string to character
21. System.out.println("Character at "+i+" Position: "+myChar);
22. }
23.
24. }
25.
26. }

Output:
Character at 0 Position: G
Character at 1 Position: u
Character at 2 Position: r
Character at 3 Position: u
Character at 4 Position: 9
Character at 5 Position: 9

Fibonacci Series Program in Java using Loops


What is Fibonacci Series?
In Fibonacci series, next number is the sum of previous two numbers. The first two
numbers of Fibonacci series are 0 and 1.

The Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, ...


Using For Loop

1. //Using For Loop


2. public class FibonacciExample {
3.
4. public static void main(String[] args)
5. {
6. // Set it to the number of elements you want in the Fibonacci Series
7. int maxNumber = 10;
8. int previousNumber = 0;
9. int nextNumber = 1;
10.
11. System.out.print("Fibonacci Series of "+maxNumber+" numbers:");
12.
13. for (int i = 1; i <= maxNumber; ++i)
14. {
15. System.out.print(previousNumber+" ");
16. /* On each iteration, we are assigning second number
17. * to the first number and assigning the sum of last two
18. * numbers to the second number
19. */
20.
21.
22. int sum = previousNumber + nextNumber;
23. previousNumber = nextNumber;
24. nextNumber = sum;
25. }
26.
27. }
28.
29. }

Program Logic:

 previousNumber is initialized to 0 and nextNumber is initialized to 1


 For Loop iterates through maxNumber
o displays the previousNumber
o calculates sum of previousNumber and nextNumber
o updates new values of previousNumber and nextNumber

Using While Loop


You can also generate Fibonacci Series using a While loop in Java.
1. //Using While Loop
2. public class FibonacciWhileExample {
3.
4. public static void main(String[] args)
5. {
6.
7. int maxNumber = 10, previousNumber = 0, nextNumber = 1;
8. System.out.print("Fibonacci Series of "+maxNumber+" numbers:");
9.
10. int i=1;
11. while(i <= maxNumber)
12. {
13. System.out.print(previousNumber+" ");
14. int sum = previousNumber + nextNumber;
15. previousNumber = nextNumber;
16. nextNumber = sum;
17. i++;
18. }
19.
20. }
21.
22. }

The only difference in the program logic is use of WHILE Loop

Fibonacci Series Based On The User Input

1. //fibonacci series based on the user input


2. import java.util.Scanner;
3. public class FibonacciExample {
4.
5. public static void main(String[] args)
6. {
7.
8. int maxNumber = 0;
9. int previousNumber = 0;
10. int nextNumber = 1;
11.
12. System.out.println("How many numbers you want in Fibonacci:");
13. Scanner scanner = new Scanner(System.in);
14. maxNumber = scanner.nextInt();
15. System.out.print("Fibonacci Series of "+maxNumber+" numbers:");
16.
17. for (int i = 1; i <= maxNumber; ++i)
18. {
19. System.out.print(previousNumber+" ");
20. /* On each iteration, we are assigning second number
21. * to the first number and assigning the sum of last two
22. * numbers to the second number
23. */
24.
25.
26. int sum = previousNumber + nextNumber;
27. previousNumber = nextNumber;
28. nextNumber = sum;
29. }
30.
31. }
32.
33. }

Program Logic:

The logic is same as earlier. Instead of hardcoding the number of elements to show
in Fibonacci Series, user is asked for the same

Java Program to Check Armstrong Number


What is Armstrong Number ?
In an Armstrong Number, the sum of power of individual digits is equal to number
itself.

In other words the following equation will hold true

xy..z = xn + yn+.....+ zn

n is number of digites in number

For example this is a 3 digit Armstrong number

370 = 33 + 73 + o3
= 27 + 343 + 0
= 370

Examples of Armstrong Numbers

0, 1, 4, 5, 9, 153, 371, 407, 8208, etc.


Let’s write this in a program:

Java Program to check whether a number is Armstrong


Number
1. //ChecktempNumber is Armstrong or not using while loop
2. package com.guru99;
3.
4. public class ArmstrongNumber {
5.
6. public static void main(String[] args) {
7.
8. int inputArmstrongNumber = 153; //Input number to check armstrong
9. int tempNumber, digit, digitCubeSum = 0;
10.
11. tempNumber = inputArmstrongNumber;
12. while (tempNumber != 0)
13. {
14.
15. /* On each iteration, remainder is powered by thetempNumber of digit
s n
16. */
17. System.out.println("Current Number is "+tempNumber);
18. digit =tempNumber % 10;
19. System.out.println("Current Digit is "+digit);
20. //sum of cubes of each digits is equal to thetempNumber itself
21. digitCubeSum = digitCubeSum + digit*digit*digit;
22. System.out.println("Current digitCubeSum is "+digit
CubeSum);
23. tempNumber /= 10;
24.
25. }
26.
27. //check giventempNumber and digitCubeSum is equal to or not
28. if(digitCubeSum == inputArmstrongNumber)
29. System.out.println(inputArmstrongNumber + " is an Armstrong Numb
er");
30. else
31. System.out.println(inputArmstrongNumber + " is not an Armstrong
Number");
32.
33. }
34.
35. }
Output
Current Number is 153
Current Digit is 3
Current digitCubeSum is 27
Current Number is 15
Current Digit is 5
Current digitCubeSum is 152
Current Number is 1
Current Digit is 1
Current digitCubeSum is 153
153 is an Armstrong Number

Java Program to Print Armstrong numbers from 0 to 999


1. //ChecktempNumber is Armstrong or not using while loop
2. package com.guru99;
3.
4. public class ArmstrongNumber {
5.
6. public static void main(String[] args) {
7. int tempNumber, digit, digitCubeSum;
8.
9. for (int inputArmstrongNumber = 0; inputArmstrongNumber < 1000; inputArms
trongNumber++) {
10. tempNumber = inputArmstrongNumber;
11. digitCubeSum = 0;
12. while (tempNumber != 0) {
13.
14. /* On each iteration, remainder is powered by thetempNumber of di
gits n
15. */
16.
17. digit = tempNumber % 10;
18.
19. //sum of cubes of each digits is equal to thetempNumber itself
20. digitCubeSum = digitCubeSum + digit * digit * digit;
21.
22. tempNumber /= 10;
23.
24. }
25.
26. //check giventempNumber and digitCubeSum is equal to or not
27. if (digitCubeSum == inputArmstrongNumber)
28. System.out.println(inputArmstrongNumber + " is an Armstrong Numbe
r");
29.
30. }
31.
32. }
33.
34. }

Output
0 is an Armstrong Number
1 is an Armstrong Number
153 is an Armstrong Number
370 is an Armstrong Number
371 is an Armstrong Number
407 is an Armstrong Number

How to Reverse a String in Java using


Recursion
In this program, we will reverse a string entered by a user.

We will create a function to reverse a string. Later we will call it recursively until all
characters are reversed.

Write a Java Program to Reverse String


1. package com.guru99;
2.
3. public class ReverseString {
4.
5. public static void main(String[] args) {
6.
7.
8. String myStr = "Guru99";
9.
10.
11. //create Method and pass and input parameter string
12. String reversed = reverseString(myStr);
13. System.out.println("The reversed string is: " + reversed);
14.
15. }
16.
17.
18. //Method take string parameter and check string is empty or not
19. public static String reverseString(String myStr)
20. {
21. if (myStr.isEmpty()){
22. System.out.println("String in now Empty");
23. return myStr;
24. }
25. //Calling Function Recursively
26. System.out.println("String to be passed in Recursive Function: "+myS
tr.substring(1));
27. return reverseString(myStr.substring(1)) + myStr.charAt(0);
28. }
29.
30. }

Output:
String to be passed in Recursive Function: uru99
String to be passed in Recursive Function: ru99
String to be passed in Recursive Function: u99
String to be passed in Recursive Function: 99
String to be passed in Recursive Function: 9
String to be passed in Recursive Function:
String in now Empty
The reversed string is: 99uruG

Check Palindrome Number Program in Java


What is Palindrome Number?
A Palindrome Number is a number that even when reversed is same as original
number
Examples of Palindrome Number

121, 393, 34043, 111, 555, 48084

Examples of Palindrome Number

LOL, MADAM
Program Logic

 Fetch the input number that needs to be checked for being a Palindrome
 Copy number into a temporary variable and reverse it.
 Compare the reversed and original number.
 If they are same, number is "palindrome number"
 Else number is not "palindrome number"

Program to check whether input number is palindrome or


not
1. package com.guru99;
2.
3. public class PalindromeNum {
4.
5. public static void main(String[] args)
6. {
7.
8. int lastDigit,sum=0,a;
9. int inputNumber=171; //It is the number to be checked for palindrom
e
10.
11. a=inputNumber;
12.
13. // Code to reverse a number
14. while(a>0)
15. { System.out.println("Input Number "+a);
16. lastDigit=a%10; //getting remainder
17. System.out.println("Last Digit "+lastDigit);
18. System.out.println("Digit "+lastDigit+ " was added to sum "+
(sum*10));
19. sum=(sum*10)+lastDigit;
20. a=a/10;
21.
22. }
23.
24. // if given number equal to sum than number is palindrome otherwise
not palindrome
25. if(sum==inputNumber)
26. System.out.println("Number is palindrome ");
27. else
28. System.out.println("Number is not palindrome");
29.
30. }
31.
32. }

Output:
Input Number 171
Last Digit 1
Digit 1 was added to sum 0
Input Number 17
Last Digit 7
Digit 7 was added to sum 10
Input Number 1
Last Digit 1
Digit 1 was added to sum 170
Number is palindrome

Bubble Sort Program in Java


What is Bubble Sort?
Bubble sort is a simple algorithm which compares the first element of the array to
the next one. If the current element of the array is numerically greater than the next
one, the elements are swapped. Likewise, the algorithm will traverse the entire
element of the array.

In this tutorial, we will create a JAVA program to implement Bubble Sort. Check the
output of the code that will help you understand the program logic

1. package com.guru99;
2.
3. public class BubbleSort {
4.
5. public static void main(String[] args)
6. {
7. int arr[] ={860,8,200,9};
8.
9. System.out.println("---Array BEFORE Bubble Sort---");
10.
11. printArray(arr);
12.
13. bubbleSort(arr);//sorting array elements using bubble sort
14.
15. System.out.println("---Array AFTER Bubble Sort---");
16.
17. printArray(arr);
18.
19. }
20. static void bubbleSort(int[] array)
21. {
22. int n = array.length;
23. int temp = 0;
24. for(int i=0; i < n; i++) // Looping through the array length
25. { System.out.println("Sort Pass Number "+(i+1));
26. for(int j=1; j < (n-i); j++)
27. {
28. System.out.println("Comparing "+ array[j-1]+ " and " + a
rray[j]);
29. if(array[j-1] > array[j])
30. {
31.
32. //swap elements
33. temp = array[j-1];
34. array[j-1] = array[j];
35. array[j] = temp;
36. System.out.println(array[j] + " is greater tha
n " + array[j-1]);
37. System.out.println("Swapping Elements: New Arra
y After Swap");
38. printArray(array);
39. }
40.
41. }
42. }
43.
44. }
45.
46. static void printArray(int[] array){
47.
48. for(int i=0; i < array.length; i++)
49. {
50. System.out.print(array[i] + " ");
51. }
52. System.out.println();
53.
54. }
55. }

Output:
860 8 200 9
Sort Pass Number 1
Comparing 860 and 8
860 is greater than 8
Swapping Elements: New Array After Swap
8 860 200 9
Comparing 860 and 200
860 is greater than 200
Swapping Elements: New Array After Swap
8 200 860 9
Comparing 860 and 9
860 is greater than 9
Swapping Elements: New Array After Swap
8 200 9 860
Sort Pass Number 2
Comparing 8 and 200
Comparing 200 and 9
200 is greater than 9
Swapping Elements: New Array After Swap
8 9 200 860
Sort Pass Number 3
Comparing 8 and 9
Sort Pass Number 4
---Array AFTER Bubble Sort---
8 9 200 860

Insertion Sort Algorithm in Java Program with


Example
Insertion sort is a simple sorting algorithm suited for small data sets. During each
iteration, the algorithm
 Removes an element from an array
 Compares it against the largest value in the array
 Moves the element to its correct location.

Here is how the process works graphically

JAVA program to sort an array using Insertion sort


algorithm.
1. package com.guru99;
2.
3. public class InsertionSortExample {
4.
5.
6. public static void main(String a[])
7. {
8. int[] myArray = {860,8,200,9};
9.
10. System.out.println("Before Insertion Sort");
11.
12. printArray(myArray);
13.
14. insertionSort(myArray);//sorting array using insertion sort
15.
16. System.out.println("After Insertion Sort");
17.
18. printArray(myArray);
19. }
20. public static void insertionSort(int arr[])
21. {
22. int n = arr.length;
23.
24. for (int i = 1; i < n; i++)
25. { System.out.println("Sort Pass Number "+(i));
26. int key = arr[i];
27. int j = i-1;
28.
29. while ( (j > -1) && ( arr [j] > key ) )
30. {
31. System.out.println("Comparing "+ key + " and " + arr [j]);
32. arr [j+1] = arr [j];
33. j--;
34. }
35. arr[j+1] = key;
36. System.out.println("Swapping Elements: New Array After Swap");
37. printArray(arr);
38. }
39. }
40. static void printArray(int[] array){
41.
42. for(int i=0; i < array.length; i++)
43. {
44. System.out.print(array[i] + " ");
45. }
46. System.out.println();
47.
48. }
49. }

Output:
Before Insertion Sort
860 8 200 9
Sort Pass Number 1
Comparing 8 and 860
Swapping Elements: New Array After Swap
8 860 200 9
Sort Pass Number 2
Comparing 200 and 860
Swapping Elements: New Array After Swap
8 200 860 9
Sort Pass Number 3
Comparing 9 and 860
Comparing 9 and 200
Swapping Elements: New Array After Swap
8 9 200 860
After Insertion Sort
8 9 200 860
Selection Sorting in Java Program with
Example
How does Selection Sort work?
Selection Sort implements a simple sorting algorithm as follows:

 Algorithm repeatedly searches for the lowest element.


 Swap current element with an element having the lowest value
 With every iteration/pass of selection sort, elements are swapped.

Java Program to implement Selection Sort

1. package com.guru99;
2.
3. public class SelectionSortAlgo {
4.
5.
6.
7. public static void main(String a[])
8. {
9. int[] myArray = {860,8,200,9};
10.
11. System.out.println("------Before Selection Sort-----");
12.
13. printArray(myArray);
14.
15.
16. selection(myArray);//sorting array using selection sort
17.
18. System.out.println("-----After Selection Sort-----");
19.
20. printArray(myArray);
21. }
22.
23. public static void selection(int[] array)
24. {
25. for (int i = 0; i < array.length - 1; i++)
26. { System.out.println("Sort Pass Number "+(i+1));
27. int index = i;
28. for (int j = i + 1; j < array.length; j++)
29. {
30. System.out.println("Comparing "+ array[index] + " and "
+ array[j]);
31. if (array[j] < array[index]){
32. System.out.println(array[index] + " is greater tha
n " + array[j] );
33. index = j;
34.
35.
36. }
37. }
38.
39. int smallerNumber = array[index];
40. array[index] = array[i];
41. array[i] = smallerNumber;
42. System.out.println("Swapping Elements: New Array After Swap"
);
43. printArray(array);
44. }
45. }
46. static void printArray(int[] array){
47.
48. for(int i=0; i < array.length; i++)
49. {
50. System.out.print(array[i] + " ");
51. }
52. System.out.println();
53.
54. }
55.
56. }

Output:
------Before Selection Sort-----
860 8 200 9
Sort Pass Number 1
Comparing 860 and 8
860 is greater than 8
Comparing 8 and 200
Comparing 8 and 9
Swapping Elements: New Array After Swap
8 860 200 9
Sort Pass Number 2
Comparing 860 and 200
860 is greater than 200
Comparing 200 and 9
200 is greater than 9
Swapping Elements: New Array After Swap
8 9 200 860
Sort Pass Number 3
Comparing 200 and 860
Swapping Elements: New Array After Swap
8 9 200 860
-----After Selection Sort-----
8 9 200 860

Top 100 Java Interview Questions with


Answers
Q1. What is the difference between an Inner Class and a Sub-Class?

Ans: An Inner class is a class which is nested within another class. An Inner class
has access rights for the class which is nesting it and it can access all variables and
methods defined in the outer class.

A sub-class is a class which inherits from another class called super class. Sub-
class can access all public and protected methods and fields of its super class.

Q2. What are the various access specifiers for Java classes?

Ans: In Java, access specifiers are the keywords used before a class name which
defines the access scope. The types of access specifiers for classes are:

1. Public : Class,Method,Field is accessible from anywhere.

2. Protected:Method,Field can be accessed from the same class to which they


belong or from the sub-classes,and from the class of same package,but not from
outside.

3. Default: Method,Field,class can be accessed only from the same package and not
from outside of it's native package.

4. Private: Method,Field can be accessed from the same class to which they belong.
Q3. What's the purpose of Static methods and static variables?

Ans: When there is a requirement to share a method or a variable between multiple


objects of a class instead of creating separate copies for each object, we use static
keyword to make a method or variable shared for all objects.

Q4. What is data encapsulation and what's its significance?

Ans: Encapsulation is a concept in Object Oriented Programming for combining


properties and methods in a single unit.

Encapsulation helps programmers to follow a modular approach for software


development as each object has its own set of methods and variables and serves its
functions independent of other objects. Encapsulation also serves data hiding
purpose.

Q5. What is a singleton class? Give a practical example of its usage.

A singleton class in java can have only one instance and hence all its methods and
variables belong to just one instance. Singleton class concept is useful for the
situations when there is a need to limit the number of objects for a class.

The best example of singleton usage scenario is when there is a limit of having only
one connection to a database due to some driver limitations or because of any
licensing issues.

Q6. What are Loops in Java? What are three types of loops?

Ans: Looping is used in programming to execute a statement or a block of statement


repeatedly. There are three types of loops in Java:

1) For Loops

For loops are used in java to execute statements repeatedly for a given number of
times. For loops are used when number of times to execute the statements is known
to programmer.

2) While Loops

While loop is used when certain statements need to be executed repeatedly until a
condition is fulfilled. In while loops, condition is checked first before execution of
statements.

3) Do While Loops
Do While Loop is same as While loop with only difference that condition is checked
after execution of block of statements. Hence in case of do while loop, statements
are executed at least once.

Q7: What is an infinite Loop? How infinite loop is declared?

Ans: An infinite loop runs without any condition and runs infinitely. An infinite loop
can be broken by defining any breaking logic in the body of the statement blocks.

Infinite loop is declared as follows:

for (;;)
{
// Statements to execute

// Add any loop breaking logic


}

Q8. What is the difference between continue and break statement?

Ans: break and continue are two important keywords used in Loops. When a break
keyword is used in a loop, loop is broken instantly while when continue keyword is
used, current iteration is broken and loop continues with next iteration.

In below example, Loop is broken when counter reaches 4.

for (counter = 0; counter & lt; 10; counter++)


system.out.println(counter);

if (counter == 4) {

break;
}

In the below example when counter reaches 4, loop jumps to next iteration and any
statements after the continue keyword are skipped for current iteration.

for (counter = 0; counter < 10; counter++)


system.out.println(counter);

if (counter == 4) {
continue;
}
system.out.println("This will not get printed when counter is 4");
}

Q9. What is the difference between double and float variables in Java?

Ans: In java, float takes 4 bytes in memory while Double takes 8 bytes in memory.
Float is single precision floating point decimal number while Double is double
precision decimal number.

Q10. What is Final Keyword in Java? Give an example.

Ans: In java, a constant is declared using the keyword Final. Value can be assigned
only once and after assignment, value of a constant can't be changed.

In below example, a constant with the name const_val is declared and assigned
avalue:

Private Final int const_val=100

When a method is declared as final,it can NOT be overridden by the


subclasses.This method are faster than any other method,because they are
resolved at complied time.

When a class is declares as final,it cannot be subclassed. Example String,Integer


and other wrapper classes.

Q11. What is ternary operator? Give an example.

Ans: Ternary operator , also called conditional operator is used to decide which
value to assign to a variable based on a Boolean value evaluation. It's denoted as ?

In the below example, if rank is 1, status is assigned a value of "Done" else


"Pending".

public class conditionTest {


public static void main(String args[]) {
String status;
int rank = 3;
status = (rank == 1) ? "Done" : "Pending";
System.out.println(status);
}
}
Q12: How can you generate random numbers in Java?

Ans:

 Using Math.random() you can generate random numbers in the range greater
than or equal to 0.1 and less than 1.0
 Using Random class in package java.util

Q13. What is default switch case? Give example.

Ans: In a switch statement, default case is executed when no other switch condition
matches. Default case is an optional case .It can be declared only once all other
switch cases have been coded.

In the below example, when score is not 1 or 2, default case is used.

public class switchExample {


int score = 4;
public static void main(String args[]) {
switch (score) {
case 1:
system.out.println("Score is 1");
break;
case 2:
system.out.println("Score is 2");
break;
default:
system.out.println("Default Case");
}
}
}

Q14. What's the base class in Java from which all classes are derived?

Ans: java.lang.object

Q15. Can main() method in Java can return any data?

Ans: In java, main() method can't return any data and hence, it's always declared
with a void return type.

Q16. What are Java Packages? What's the significance of packages?


Ans: In Java, package is a collection of classes and interfaces which are bundled
together as they are related to each other. Use of packages helps developers to
modularize the code and group the code for proper re-use. Once code has been
packaged in Packages, it can be imported in other classes and used.

Q17. Can we declare a class as Abstract without having any abstract method?

Ans: Yes we can create an abstract class by using abstract keyword before class
name even if it doesn't have any abstract method. However, if a class has even one
abstract method, it must be declared as abstract otherwise it will give an error.

Q18. What's the difference between an Abstract Class and Interface in Java?

Ans: The primary difference between an abstract class and interface is that an
interface can only possess declaration of public static methods with no concrete
implementation while an abstract class can have members with any access
specifiers (public, private etc) with or without concrete implementation.

Another key difference in the use of abstract classes and interfaces is that a class
which implements an interface must implement all the methods of the interface while
a class which inherits from an abstract class doesn't require implementation of all
the methods of its super class.

A class can implement multiple interfaces but it can extend only one abstract class.

Q19. What are the performance implications of Interfaces over abstract


classes?

Ans: Interfaces are slower in performance as compared to abstract classes as extra


indirections are required for interfaces. Another key factor for developers to take into
consideration is that any class can extend only one abstract class while a class can
implement many interfaces.

Use of interfaces also puts an extra burden on the developers as any time an
interface is implemented in a class; developer is forced to implement each and every
method of interface.

Q20. Does Importing a package imports its sub-packages as well in Java?

Ans: In java, when a package is imported, its sub-packages aren't imported and
developer needs to import them separately if required.

For example, if a developer imports a package university.*, all classes in the


package named university are loaded but no classes from the sub-package are
loaded. To load the classes from its sub-package ( say department), developer has
to import it explicitly as follows:

Import university.department.*

Q21. Can we declare the main method of our class as private?

Ans: In java, main method must be public static in order to run any application
correctly. If main method is declared as private, developer won't get any compilation
error however, it will not get executed and will give a runtime error.

Q22. How can we pass argument to a function by reference instead of pass by


value?

Ans: In java, we can pass argument to a function only by value and not by reference.

Q23. How an object is serialized in java?

Ans: In java, to convert an object into byte stream by serialization, an interface with
the name Serializable is implemented by the class. All objects of a class
implementing serializable interface get serialized and their state is saved in byte
stream.

Q24. When we should use serialization?

Ans: Serialization is used when data needs to be transmitted over the network.
Using serialization, object's state is saved and converted into byte stream .The byte
stream is transferred over the network and the object is re-created at destination.

Q25. Is it compulsory for a Try Block to be followed by a Catch Block in Java


for Exception handling?

Ans: Try block needs to be followed by either Catch block or Finally block or both.
Any exception thrown from try block needs to be either caught in the catch block or
else any specific tasks to be performed before code abortion are put in the Finally
block.

Q26. Is there any way to skip Finally block of exception even if some
exception occurs in the exception block?

Ans: If an exception is raised in Try block, control passes to catch block if it exists
otherwise to finally block. Finally block is always executed when an exception occurs
and the only way to avoid execution of any statements in Finally block is by aborting
the code forcibly by writing following line of code at the end of try block:
System.exit(0);

Q27. When the constructor of a class is invoked?

Ans: The constructor of a class is invoked every time an object is created with new
keyword.

For example, in the following class two objects are created using new keyword and
hence, constructor is invoked two times.

public class const_example {

const_example() {

system.out.println("Inside constructor");
}
public static void main(String args[]) {

const_example c1 = new const_example();

const_example c2 = new const_example();


}
}

Q28. Can a class have multiple constructors?

Ans: Yes, a class can have multiple constructors with different parameters. Which
constructor gets used for object creation depends on the arguments passed while
creating the objects.

Q29. Can we override static methods of a class?

Ans: We cannot override static methods. Static methods belong to a class and not to
individual objects and are resolved at the time of compilation (not at runtime).Even if
we try to override static method,we will not get an complitaion error,nor the impact of
overriding when running the code.

Q30. In the below example, what will be the output?

public class superclass {

public void displayResult() {

system.out.println("Printing from superclass");


}

public class subclass extends superclass {

public void displayResult() {

system.out.println("Displaying from subClass");

super.displayResult();

public static void main(String args[]) {

subclass obj = new subclass();

obj.displayResult();

Ans: Output will be:

Displaying from subclass

Displaying from superclass

Q31. Is String a data type in java?

Ans: String is not a primitive data type in java. When a string is created in java, it's
actually an object of Java.Lang.String class that gets created. After creation of this
string object, all built-in methods of String class can be used on the string object.

Q32. In the below example, how many String Objects are created?

String s1="I am Java Expert";

String s2="I am C Expert";

String s3="I am Java Expert";


Ans: In the above example, two objects of Java.Lang.String class are created. s1
and s3 are references to same object.

Q33. Why Strings in Java are called as Immutable?

Ans: In java, string objects are called immutable as once value has been assigned to
a string, it can't be changed and if changed, a new object is created.

In below example, reference str refers to a string object having value "Value one".

String str="Value One";

When a new value is assigned to it, a new String object gets created and the
reference is moved to the new object.

str="New Value";

Q34. What's the difference between an array and Vector?

Ans: An array groups data of same primitive type and is static in nature while vectors
are dynamic in nature and can hold data of different data types.

Q35. What is multi-threading?

Ans: Multi threading is a programming concept to run multiple tasks in a concurrent


manner within a single program. Threads share same process stack and running in
parallel. It helps in performance improvement of any program.

Q36. Why Runnable Interface is used in Java?

Ans: Runnable interface is used in java for implementing multi threaded applications.
Java.Lang.Runnable interface is implemented by a class to support multi threading.

Q37. What are the two ways of implementing multi-threading in Java?

Ans: Multi threaded applications can be developed in Java by using any of the
following two methodologies:

1. By using Java.Lang.Runnable Interface. Classes implement this interface to


enable multi threading. There is a Run() method in this interface which is
implemented.

2. By writing a class that extend Java.Lang.Thread class.


Q38. When a lot of changes are required in data, which one should be a
preference to be used? String or StringBuffer?

Ans: Since StringBuffers are dynamic in nature and we can change the values of
StringBuffer objects unlike String which is immutable, it's always a good choice to
use StringBuffer when data is being changed too much. If we use String in such a
case, for every data change a new String object will be created which will be an
extra overhead.

Q39. What's the purpose of using Break in each case of Switch Statement?

Ans: Break is used after each case (except the last one) in a switch so that code
breaks after the valid case and doesn't flow in the proceeding cases too.

If break isn't used after each case, all cases after the valid case also get executed
resulting in wrong results.

Q40. How garbage collection is done in Java?

Ans: In java, when an object is not referenced any more, garbage collection takes
place and the object is destroyed automatically. For automatic garbage collection
java calls either System.gc() method or Runtime.gc() method.

Q41. How we can execute any code even before main method?

Ans: If we want to execute any statements before even creation of objects at load
time of class, we can use a static block of code in the class. Any statements inside
this static block of code will get executed once at the time of loading the class even
before creation of objects in the main method.

Q42. Can a class be a super class and a sub-class at the same time? Give
example.

Ans: If there is a hierarchy of inheritance used, a class can be a super class for
another class and a sub-class for another one at the same time.

In the example below, continent class is sub-class of world class and it's super class
of country class.

public class world {

..........

}
public class continenet extends world {
............

}
public class country extends continent {

......................

Q43. How objects of a class are created if no constructor is defined in the


class?

Ans: Even if no explicit constructor is defined in a java class, objects get created
successfully as a default constructor is implicitly used for object creation. This
constructor has no parameters.

Q44. In multi-threading how can we ensure that a resource isn't used by


multiple threads simultaneously?

Ans: In multi-threading, access to the resources which are shared among multiple
threads can be controlled by using the concept of synchronization. Using
synchronized keyword, we can ensure that only one thread can use shared resource
at a time and others can get control of the resource only once it has become free
from the other one using it.

Q45. Can we call the constructor of a class more than once for an object?

Ans: Constructor is called automatically when we create an object using new


keyword. It's called only once for an object at the time of object creation and hence,
we can't invoke the constructor again for an object after its creation.

Q46. There are two classes named classA and classB. Both classes are in the
same package. Can a private member of classA can be accessed by an object
of classB?

Ans: Private members of a class aren't accessible outside the scope of that class
and any other class even in the same package can't access them.

Q47. Can we have two methods in a class with the same name?

Ans: We can define two methods in a class with the same name but with different
number/type of parameters. Which method is to get invoked will depend upon the
parameters passed.
For example in the class below we have two print methods with same name but
different parameters. Depending upon the parameters, appropriate one will be
called:

public class methodExample {

public void print() {

system.out.println("Print method without parameters.");

public void print(String name) {

system.out.println("Print method with parameter");

public static void main(String args[]) {

methodExample obj1 = new methodExample();

obj1.print();

obj1.print("xx");

Q48. How can we make copy of a java object?

Ans: We can use the concept of cloning to create copy of an object. Using clone, we
create copies with the actual state of an object.

Clone() is a method of Cloneable interface and hence, Cloneable interface needs to


be implemented for making object copies.

Q49. What's the benefit of using inheritance?

Ans: Key benefit of using inheritance is reusability of code as inheritance enables


sub-classes to reuse the code of its super class. Polymorphism (Extensibility ) is
another great benefit which allow new functionality to be introduced without effecting
existing derived classes.
Q50. What's the default access specifier for variables and methods of a class?

Ans: Default access specifier for variables and method is package protected i.e
variables and class is available to any other class but in the same package,not
outside the package.

Q51. Give an example of use of Pointers in Java class.

Ans: There are no pointers in Java. So we can't use concept of pointers in Java.

Q52. How can we restrict inheritance for a class so that no class can be
inherited from it?

Ans: If we want a class not to be extended further by any class, we can use the
keyword Finalwith the class name.

In the following example, Stone class is Final and can't be extend

public Final Class Stone {


// Class methods and Variables
}

Q53. What's the access scope of Protected Access specifier?

Ans: When a method or a variable is declared with Protected access specifier, it


becomes accessible in the same class,any other class of the same package as well
as a sub-class.

Modifier Class Package Subclass World

public Y Y Y Y

protected Y Y Y N

no modifier Y Y N N

private Y N N N

Q54. What's difference between Stack and Queue?

Ans: Stack and Queue both are used as placeholder for a collection of data. The
primary difference between a stack and a queue is that stack is based on Last in
First out (LIFO) principle while a queue is based on FIFO (First In First Out)
principle.
Q55. In java, how we can disallow serialization of variables?

Ans: If we want certain variables of a class not to be serialized, we can use the
keyword transient while declaring them. For example, the variable trans_var below
is a transient variable and can't be serialized:

public class transientExample {


private transient trans_var;
// rest of the code
}

Q56. How can we use primitive data types as objects?

Ans: Primitive data types like int can be handled as objects by the use of their
respective wrapper classes. For example, Integer is a wrapper class for primitive
data type int. We can apply different methods to a wrapper class, just like any other
object.

Q57. Which types of exceptions are caught at compile time?

Ans: Checked exceptions can be caught at the time of program compilation.


Checked exceptions must be handled by using try catch block in the code in order to
successfully compile the code.

Q58. Describe different states of a thread.

Ans: A thread in Java can be in either of the following states:

 Ready: When a thread is created, it's in Ready state.


 Running: A thread currently being executed is in running state.
 Waiting: A thread waiting for another thread to free certain resources is in
waiting state.
 Dead: A thread which has gone dead after execution is in dead state.

Q59. Can we use a default constructor of a class even if an explicit


constructor is defined?

Ans: Java provides a default no argument constructor if no explicit constructor is


defined in a Java class. But if an explicit constructor has been defined, default
constructor can't be invoked and developer can use only those constructors which
are defined in the class.

Q60. Can we override a method by using same method name and arguments
but different return types?
Ans: The basic condition of method overriding is that method name, arguments as
well as return type must be exactly same as is that of the method being overridden.
Hence using a different return type doesn't override a method.

Q61.What will be the output of following piece of code?

public class operatorExample {

public static void main(String args[]) {

int x = 4;

system.out.println(x++);
}
}

Ans: In this case postfix ++ operator is used which first returns the value and then
increments. Hence it's output will be 4.

Q61. A person says that he compiled a java class successfully without even
having a main method in it? Is it possible?

Ans: main method is an entry point of Java class and is required for execution of the
program however; a class gets compiled successfully even if it doesn't have a main
method. It can't be run though.

Q62. Can we call a non-static method from inside a static method?

Ans: Non-Static methods are owned by objects of a class and have object level
scope and in order to call the non-Static methods from a static block (like from a
static main method), an object of the class needs to be created first. Then using
object reference, these methods can be invoked.

Q63. What are the two environment variables that must be set in order to run
any Java programs?

Ans: Java programs can be executed in a machine only once following two
environment variables have been properly set:

1. PATH variable
2. CLASSPATH variable

Q64. Can variables be used in Java without initialization?


Ans: In Java, if a variable is used in a code without prior initialization by a valid
value, program doesn't compile and gives an error as no default value is assigned to
variables in Java.

Q65. Can a class in Java be inherited from more than one class?

Ans: In Java, a class can be derived from only one class and not from multiple
classes. Multiple inheritances is not supported by Java.

Q66. Can a constructor have different name than a Class name in Java?

Ans: Constructor in Java must have same name as the class name and if the name
is different, it doesn't act as a constructor and compiler thinks of it as a normal
method.

Q67. What will be the output of Round(3.7) and Ceil(3.7)?

Ans: Round(3.7) returns 4 and Ceil(3.7) returns 4.

Q68: Can we use goto in Java to go to a particular line?

Ans: In Java, there is not goto keyword and java doesn't support this feature of going
to a particular labeled line.

Q69. Can a dead thread be started again?

Ans: In java, a thread which is in dead state can't be started again. There is no way
to restart a dead thread.

Q70. Is the following class declaration correct?

Ans:

public abstract final class testClass {


// Class methods and variables
}

Ans: The above class declaration is incorrect as an abstract class can't be declared
as Final.

Q71. Is JDK required on each machine to run a Java program?

Ans: JDK is development Kit of Java and is required for development only and to run
a Java program on a machine, JDK isn't required. Only JRE is required.
Q72. What's the difference between comparison done by equals method and
== operator?

Ans: In Java, equals() method is used to compare the contents of two string objects
and returns true if the two have same value while == operator compares the
references of two string objects.

In the following example, equals() returns true as the two string objects have same
values. However == operator returns false as both string objects are referencing to
different objects:

public class equalsTest {

public static void main(String args[]) {

String str1 = new String("Hello World");

String str2 = new String("Hello World");

if (str1.equals(str2))

{ // this condition is true

System.out.println("str1 and str2 are equal in terms of values");

if (str1 == str2) {

//This condition is true

System.out.println("Both strings are referencing same object");

} else

// This condition is NOT true

System.out.println("Both strings are referencing different objects");

}
}

Q73. Is it possible to define a method in Java class but provide it's


implementation in the code of another language like C?

Ans: Yes, we can do this by use of native methods. In case of native method based
development, we define public static methods in our Java class without its
implementation and then implementation is done in another language like C
separately.

Q74. How are destructors defined in Java?

Ans: In Java, there are no destructors defined in the class as there is no need to do
so. Java has its own garbage collection mechanism which does the job
automatically by destroying the objects when no longer referenced.

Q75. Can a variable be local and static at the same time?

Ans: No a variable can't be static as well as local at the same time. Defining a local
variable as static gives compilation error.

Q76. Can we have static methods in an Interface?

Ans: Static methods can't be overridden in any class while any methods in an
interface are by default abstract and are supposed to be implemented in the classes
being implementing the interface. So it makes no sense to have static methods in an
interface in Java.

Q77. In a class implementing an interface, can we change the value of any


variable defined in the interface?

Ans: No, we can't change the value of any variable of an interface in the
implementing class as all variables defined in the interface are by default public,
static and Final and final variables are like constants which can't be changed later.

Q78. Is it correct to say that due to garbage collection feature in Java, a java
program never goes out of memory?

Ans: Even though automatic garbage collection is provided by Java, it doesn't


ensure that a Java program will not go out of memory as there is a possibility that
creation of Java objects is being done at a faster pace compared to garbage
collection resulting in filling of all the available memory resources.
So, garbage collection helps in reducing the chances of a program going out of
memory but it doesn't ensure that.

Q79. Can we have any other return type than void for main method?

Ans: No, Java class main method can have only void return type for the program to
get successfully executed.

Nonetheless , if you absolutely must return a value to at the completion of main


method , you can use System.exit(int status)

Q80. I want to re-reach and use an object once it has been garbage collected.
How it's possible?

Ans: Once an object has been destroyed by garbage collector, it no longer exists on
the heap and it can't be accessed again. There is no way to reference it again.

Q81. In Java thread programming, which method is a must implementation for


all threads?

Ans: Run() is a method of Runnable interface that must be implemented by all


threads.

Q82. I want to control database connections in my program and want that only
one thread should be able to make database connection at a time. How can I
implement this logic?

Ans: This can be implemented by use of the concept of synchronization. Database


related code can be placed in a method which hs synchronized keyword so that
only one thread can access it at a time.

Q83. How can an exception be thrown manually by a programmer?

Ans: In order to throw an exception in a block of code manually, throw keyword is


used. Then this exception is caught and handled in the catch block.

public void topMethod() {


try {
excMethod();
} catch (ManualException e) {}
}

public void excMethod {


String name = null;
if (name == null) {
throw (new ManualException("Exception thrown manually ");
}
}

Q84. I want my class to be developed in such a way that no other class (even
derived class) can create its objects. How can I do so?

Ans: If we declare the constructor of a class as private, it will not be accessible by


any other class and hence, no other class will be able to instantiate it and formation
of its object will be limited to itself only.

Q85. How objects are stored in Java?

Ans: In java, each object when created gets a memory space from a heap. When an
object is destroyed by a garbage collector, the space allocated to it from the heap is
re-allocated to the heap and becomes available for any new objects.

Q86. How can we find the actual size of an object on the heap?

Ans: In java, there is no way to find out the exact size of an object on the heap.

Q87. Which of the following classes will have more memory allocated?

Class A: Three methods, four variables, no object

Class B: Five methods, three variables, no object

Ans: Memory isn't allocated before creation of objects. Since for both classes, there
are no objects created so no memory is allocated on heap for any class.

Q88. What happens if an exception is not handled in a program?

Ans: If an exception is not handled in a program using try catch blocks, program
gets aborted and no statement executes after the statement which caused exception
throwing.

Q89. I have multiple constructors defined in a class. Is it possible to call a


constructor from another constructor's body?

Ans: If a class has multiple constructors, it's possible to call one constructor from the
body of another one using this().

Q90. What's meant by anonymous class?


Ans: An anonymous class is a class defined without any name in a single line of
code using new keyword.

For example, in below code we have defined an anonymous class in one line of
code:

public java.util.Enumeration testMethod()

return new java.util.Enumeration()

@Override

public boolean hasMoreElements()

// TODO Auto-generated method stub

return false;

@Override

public Object nextElement()

// TODO Auto-generated method stub

return null;

Q91. Is there a way to increase the size of an array after its declaration?
Ans: Arrays are static and once we have specified its size, we can't change it. If we
want to use such collections where we may require a change of size ( no of items),
we should prefer vector over array.

Q92. If an application has multiple classes in it, is it okay to have a main


method in more than one class?

Ans: If there is main method in more than one classes in a java application, it won't
cause any issue as entry point for any application will be a specific class and code
will start from the main method of that particular class only.

Q93. I want to persist data of objects for later use. What's the best approach to
do so?

Ans: The best way to persist data for future use is to use the concept of serialization.

Q94. What is a Local class in Java?

Ans: In Java, if we define a new class inside a particular block, it's called a local
class. Such a class has local scope and isn't usable outside the block where its
defined.

Q95. String and StringBuffer both represent String objects. Can we compare
String and StringBuffer in Java?

Ans: Although String and StringBuffer both represent String objects, we can't
compare them with each other and if we try to compare them, we get an error.

Q96. Which API is provided by Java for operations on set of objects?

Ans: Java provides a Collection API which provides many useful methods which can
be applied on a set of objects. Some of the important classes provided by Collection
API include ArrayList, HashMap, TreeSet and TreeMap.

Q97. Can we cast any other type to Boolean Type with type casting?

Ans: No, we can neither cast any other primitive type to Boolean data type nor can
cast Boolean data type to any other primitive data type.

Q98. Can we use different return types for methods when overridden?

Ans: The basic requirement of method overriding in Java is that the overridden
method should have same name, and parameters.But a method can be overridden
with a different return type as long as the new return type extends the original.
For example , method is returning a reference type.

Class B extends A {

A method(int x) {

//original method

B method(int x) {

//overridden method

Q99. What's the base class of all exception classes?

Ans: In Java, Java.lang.Throwable is the super class of all exception classes and
all exception classes are derived from this base class.

Q100. What's the order of call of constructors in inheritiance?

Ans: In case of inheritance, when a new object of a derived class is created, first the
constructor of the super class is invoked and then the constructor of the derived
class is invoked.

Potrebbero piacerti anche