Introduction To Java Programming
Introduction To Java Programming
Java Tutorials
JAVA was developed by Sun Microsystems Inc in 1991, later acquired by Oracle
Corporation. It was conceived by James Gosling and Patrick Naughton. It is a simple
programming language. Writing, compiling and debugging a program is easy in java. It
helps to create modular programs and reusable code.
1. Abstraction
2. Encapsulation
3. Inheritance
4. Polymorphism
Simple
Java is considered as one of simple language because it does not have complex features like
Operator overloading, Multiple inheritance, pointers and Explicit memory allocation.
Robust Language
Two main problems that cause program failures are memory management mistakes and
mishandled runtime errors. Java handles both of them efficiently.
1) Memory management mistakes can be overcome by garbage collection. Garbage
collection is automatic de-allocation of objects which are no longer needed.
2) Mishandled runtime errors are resolved by Exception Handling procedures.
Secure
It provides a virtual firewall between the application and the computer. Java codes are
confined within Java Runtime Environment (JRE) thus it does not grant unauthorized access
on the system resources.
Java is distributed
Multithreading
Portable
As discussed above, java code that is written on one machine can run on another machine.
The platform independent byte code can be carried to any platform for execution that makes
java code portable.
To create a java code an editor such as notepad, text pad or an IDE like eclipse can be used.
In the above program the class FirstJavaProgram has public access and hence declared
public.
‘class’ is the keyword used to create a class.
For running stand-alone programs ‘main’ method is needed which has a signature similar to
the one defined in the above program.
‘Main’ method takes an array of strings as an argument. The name of the array can be
anything.
To display the output, pass the string as an argument to the method [Link].
Steps for compilation and Execution
The following are the general programming errors and the solution for them while running on
windows machine.
Another Example
If you are a beginner and feel hard to understand the below example then just skip it and try
to understand it once you finished reading all of my linked tutorials. After reading all tutorials
it would be easy for you to learn things much faster.
package FirstCode
import [Link].*;
class WelcomeMessage
{
printMessage()
{
[Link]("Hello World");
}
}
class Myclass
{
public static void main(String []args)
{
WelcomeMessage obj=new WelcomeMessage ();
[Link]();
}
}
a) Line 1. The package FirstCode creates a folder to store the class files generated after
compilation
b) Line2. It imports the class library [Link] and its subsequent classes
c) Line 3. Initiates a class with the name WelcomeMessage
d) Line 5. Declares a method with name printMessage
e) Line 7. Defines the actual working code of the method
f) Line 10. Initiates the class having the main method; it should bear the name of the file :
[Link]
g) Line 12. Declares the main method
h) Line 14. Initiates the creation of the object
i) Line 15. Calls the method printMessage () with the help of the object
j) The above code is saved and compiled to run on JVM
1) The programming pattern is divided into classes which has meth0d definitions
2) This assists in distributing the code into smaller units
3) The libraries can be used over and over again
4) These codes generated here can be called in another program if required
5) The memory allocation is done only after the execution of the new keyword
6) It gets easier to collect memory that does not has any future use
Demon Threads
It has been Run by JVM for itself. Used for garbage collection. JVM decides on a thread for
being a demon thread
Non-demon threads
main() is the initial and non-demon thread. Other implemented threads are also non-demon
threads. The JVM is active till any non-demon thread is active.
Execution on JVM
1) JVM executes Java byte codes
2) Other programming language codes if converted to adequate Java byte code can be
executed on JVM
3) JVM is different for different platforms and can also act as a platform itself
4) JVM supports automatic error handling by intercepting the errors which can be controlled
5) This feature is useful in platform independency and multi user ability of Java.
Compilation
1) The compiler requires to know the TYPE of every CLASS used in the program source
code
2) This is done by setting a default user environment variable CLASSPATH
3) The Javac (Java Compiler) reads the program and converts it into byte code files called as
class files
In Java we have three types of basic loops: for, while & do-while. In this article we are going
to discuss about for loop. We will cover following topics in this article: a) What is for loop b)
syntax of for loop c) example of for loop d) for loop flow diagram e) infinite for loop.
It executes a block of statements repeatedly until the specified condition returns false.
Mind the semicolon (;) after initialization and condition in the above syntax.
Confused??
Don’t worry let see an example to understand it better.
This is an infinite loop as the condition would never return false. The initialization step is
setting up the value of variable i to 1, since we are incrementing the value of i, it would
always be greater than 1 (the Boolean expression: i>1) so it would never return false. This
would eventually lead to the infinite loop condition. Thus it is important to see the co-
ordination among Boolean expression and increment/decrement to determine whether the
loop would terminate at some point of time or not.
// infinite loop
for ( ; ; ) {
// statement(s)
}
Here we are iterating and displaying array elements using the for loop.
class ForLoopExample3 {
public static void main(String args[]){
int arr[4]={2,11,45,9};
//i starts with 0 as array index starts with 0 too
for(int i=0; i<4; i++){
[Link](arr[i]);
}
}
}
Output:
2
11
45
9
In the last post we discussed about for loop. In this tutorial we are going to discuss about
while loop with the help of examples and flow diagrams. We will cover following topics in
this article: a) Introduction to while loop b) Syntax of while loop c) Flow diagram of while
loop d) While loop example e) infinite while loop.
The logic in while loop is simple it executes the block of statements when the Boolean
expression returns true. It gets terminated when the Boolean expression returns false.
This loop would never end, its an infinite while loop. This is because condition is i>1 which
would always be true as we are incrementing the value of i inside while loop.
while (true){
statement(s);
}
Here we are iterating and displaying array elements using while loop.
class WhileLoopExample3 {
public static void main(String args[]){
int arr[4]={2,11,45,9};
//i starts with 0 as array index starts with 0 too
int i=0;
while(i<4){
[Link](arr[i]);
i++;
}
}
}
Output:
2
11
45
9
We have already covered for loop and while loop in the previous tutorials. In this tutorial we
are going to discuss about do-while loop with the help of examples and flow diagrams. We
will cover following topics in this article: a) Introduction to do-while loop b) Syntax of do-
while loop c) do-while loop example
do-while loop is similar to while loop, however there is a single difference between these
two. Unlike while loop, do-while guarantees at-least one execution of block of statements.
This happens because the do-while loop evaluates the boolean expression at the end of the
loop’s body. Therefore the set of statements gets executed at-least once before the check of
boolean expression.
Here we are iterating and displaying array elements using do-while loop.
class DoWhileLoopExample2 {
public static void main(String args[]){
int arr[4]={2,11,45,9};
//i starts with 0 as array index starts with 0 too
int i=0;
do{
[Link](arr[i]);
i++;
}while(i<4);
}
}
Output:
2
11
45
9
The program will prompt user to input the number and then it will reverse the same number
using while loop.
import [Link];
class ReverseNumberWhile
{
public static void main(String args[])
{
int num=0;
int reversenum =0;
[Link]("Input your number and press enter: ");
//This statement will capture the user input
Scanner in = new Scanner([Link]);
//Captured input would be stored in number num
num = [Link]();
//While Loop: Logic to find out the reverse number
while( num != 0 )
{
reversenum = reversenum * 10;
reversenum = reversenum + num%10;
num = num/10;
}
Output:
Output:
class ReverseNumberDemo
{
public static void main(String args[])
{
int num=123456789;
int reversenum =0;
while( num != 0 )
{
reversenum = reversenum * 10;
reversenum = reversenum + num%10;
num = num/10;
}
[Link]("Reverse of specified number is: "+reversenum);
}
}
Output:
In this tutorial we will see how to calculate area and circumference of circle in Java.
There are two ways to do this:
1) With user interaction: Program will prompt user to enter the radius of the circle
2) Without user interaction: The radius value would be specified in the program itself.
Program 1:
/**
* @author: [Link]
* @description: Program to calculate area and circumference of circle
* with user interaction. User will be prompt to enter the radius and
* the result will be calculated based on the provided radius value.
*/
import [Link];
class CircleDemo
{
static Scanner sc = new Scanner([Link]);
public static void main(String args[])
{
[Link]("Enter the radius: ");
/*We are storing the entered radius in double
* because a user can enter radius in decimals
*/
double radius = [Link]();
//Area = PI*radius*radius
double area = [Link] * (radius * radius);
[Link]("The area of circle is: " + area);
//Circumference = 2*PI*radius
double circumference= [Link] * 2*radius;
[Link]( "The circumference of the circle
is:"+circumference) ;
}
}
Output:
Program 2:
/**
* @author: [Link]
* @description: Program to calculate area and circumference of circle
* without user interaction. You need to specify the radius value in
* program itself.
*/
class CircleDemo2
{
public static void main(String args[])
{
int radius = 3;
double area = [Link] * (radius * radius);
[Link]("The area of circle is: " + area);
double circumference= [Link] * 2*radius;
[Link]( "The circumference of the circle
is:"+circumference) ;
}
}
Output:
Here we will see how to calculate area of triangle. We will see two following programs to do
this:
1) Program 1: Prompt user for base-width and height of triangle.
2) Program 2: No user interaction: Width and height are specified in the program itself.
Program 1:
/**
* @author: [Link]
* @description: Program to Calculate area of Triangle in Java
* with user interaction. Program will prompt user to enter the
* base width and height of the triangle.
*/
import [Link];
class AreaTriangleDemo {
public static void main(String args[]) {
Scanner scanner = new Scanner([Link]);
//Area = (width*height)/2
double area = (base* height)/2;
[Link]("Area of Triangle is: " + area);
}
}
Output:
/**
* @author: [Link]
* @description: Program to Calculate area of Triangle
* with no user interaction.
*/
class AreaTriangleDemo2 {
public static void main(String args[]) {
double base = 20.0;
double height = 110.5;
double area = (base* height)/2;
[Link]("Area of Triangle is: " + area);
}
}
Output:
In this tutorial we will see how to sum up all the elements of an array.
/**
* @author: [Link]
* @description: Get sum of array elements
*/
class SumOfArray{
public static void main(String args[]){
int[] array = {10, 20, 30, 40, 50, 10};
int sum = 0;
//Advanced for loop
for( int num : array) {
sum = sum+num;
}
[Link]("Sum of array elements is:"+sum);
}
}
Output:
/**
* @author: [Link]
* @description: User would enter the 10 elements
* and the program will store them into an array and
* will display the sum of them.
*/
import [Link];
class SumDemo{
public static void main(String args[]){
Scanner scanner = new Scanner([Link]);
int[] array = new int[10];
int sum = 0;
[Link]("Enter the elements:");
for (int i=0; i<10; i++)
{
array[i] = [Link]();
}
for( int num : array) {
sum = sum+num;
}
[Link]("Sum of array elements is:"+sum);
}
}
Output:
This program will prompt user to enter a number and then it will check and display whether
the input number is prime or not.
import [Link];
class PrimeCheck
{
public static void main(String args[])
{
int temp;
boolean isPrime=true;
Scanner scan= new Scanner([Link]);
[Link]("Enter a number for check:");
//capture the input in an integer
int num=[Link]();
for(int i=2;i<=num/2;i++)
{
temp=num%i;
if(temp==0)
{
isPrime=false;
break;
}
}
//If isPrime is true then the number is prime else not
if(isPrime)
[Link](num + " is Prime Number");
else
[Link](num + " is not Prime Number");
}
}
Output:
Output 2:
class CheckEvenOdd
{
public static void main(String args[])
{
int num;
[Link]("Enter an Integer number:");
Output 1:
Output 2:
Example Program:
This program uses linear search algorithm to find out a number among all other numbers
entered by user.
Output 2:
This program uses binary search algorithm to search an element in given list of elements.
Output 1:
Output 2:
In the below program, we are using the nextInt() method of Random class to serve our
purpose.
Output:
Random Numbers:
***************
135
173
5
17
15
The output of above program would not be same everytime. It would generate any 5 random
numbers between 0 and 200 whenever you run this code. For e.g. When I ran it second time,
it gave me the below output, which is entirely different from the above one.
Output 2:
Random Numbers:
***************
46
99
191
7
134
Java Program to find duplicate
Characters in a String
JAVA EXAMPLES
This program would find out the duplicate characters in a String and
would display the count of them.
import [Link];
import [Link];
import [Link];
//Create a HashMap
Map<Character, Integer> map = new HashMap<Character, Integer>();
[Link]("\nString: ChaitanyaSingh");
[Link]("-------------------------");
[Link]("ChaitanyaSingh");
[Link]("\nString: #@$@!#$%!!%@");
[Link]("-------------------------");
[Link]("#@$@!#$%!!%@");
}
}
Output:
String: [Link]
-------------------------
Char e 2
Char B 2
Char n 2
Char o 3
String: ChaitanyaSingh
-------------------------
Char a 3
Char n 2
Char h 2
Char i 2
String: #@$@!#$%!!%@
-------------------------
Char # 2
Char ! 3
Char @ 3
Char $ 2
Char % 2
import [Link];
class BinaryToDecimal {
public static void main(String args[]){
Scanner input = new Scanner( [Link] );
[Link]("Enter a binary number: ");
String binaryString =[Link]();
[Link]("Output: "+[Link](binaryString,2));
}
}
Output:
Enter a binary number: 1101
Output: 13
int decimal = 0;
int p = 0;
while(true){
if(binaryNumber == 0){
break;
} else {
int temp = binaryNumber%10;
decimal += temp*[Link](2, p);
binaryNumber = binaryNumber/10;
p++;
}
}
return decimal;
}
In this tutorial we are gonna see how to accept input from user. We
are using Scanner class to get the input. In the below example we are
getting input String, integer and a float number. For this we are using
following methods:
1) public String nextLine(): For getting input String
2) public int nextInt(): For integer input
3) public float nextFloat(): For float input
Example:
import [Link];
class GetInputData
{
public static void main(String args[])
{
int num;
float fnum;
String str;
OOPs Basics
4. Method overloading vs
5. Constructors 6. Constructor overloading
Overriding
8. Constructors in
7. private constructor 9. Constructor chaining
interfaces
31. Abstract class vs interface 32. Access modifiers 33. Packages in java
Note: Above are the links of separate detailed tutorials on each topic.
However if want to brush up the things for interview, below is a brief of
each of the above topic which will help you re-call the things.
Object Oriented Programming is a programming method that
combines:
a) Data
b) Instructions for processing that data
into a self-sufficient ‘object’ that can be used within a program or in other
programs.
Advantage of Object Oriented Programming
a) Objects are modeled on real world entities.
b) This enables modeling complex systems of real world into manageable
software solutions.
Programming techniques
a) Unstructured Programming (Assembly language programming)
b) Procedural Programming (Assembly language, C programming)
c) Object Oriented Programming (C++, Java, Smalltalk, C#, Objective
C)
Unstructured Programming
This consists of just writing the sequence of commands or statements in
the main program, which modifies the state maintained in Global Data.
Example: Assembly Language programs.
ClassName Objectname;
Object definition is done by calling the class constructor
Encapsulation
Encapsulation means the localization of the information or knowledge
within an object.
Encapsulation is also called as “Information Hiding”.
1) Objects encapsulate data and implementation details. To the outside
world, an object is a black box that exhibits a certain behavior.
2) The behavior of this object is what which is useful for the external world
or other objects.
3) An object exposes its behavior by means of methods or functions.
4) The set of functions an object exposes to other objects or external
world acts as the interface of the object.
Benefits of Encapsulation
1) The functionality where in we can change the implementation code
without breaking the code of others who use our code is the biggest
benefit of Encapsulation.
2) Here in encapsulation we hide the implementation details behind a
public programming interface. By interface, we mean the set of accessible
methods our code makes available for other code to call—in other words,
our code’s API.
3) By hiding implementation details, We can rework on our method code
at a later point of time, each time we change out implementation this
should not affect the code which has a reference to our code, as our API
still remains the same
How to bring in Encapsulation
1) Make the instance variables protected.
2) Create public accessor methods and use these methods from within the
calling code.
3) Use the JavaBeans naming convention of getter and setter.
Eg: getPropertyName, setPropertyName.
Example for encapsulation
class EmployeeCount
{
private int NoOfEmployees = 0;
public void setNoOfEmployees (int count)
{
NoOfEmployees = count;
}
public double getNoOfEmployees ()
{
return NoOfEmployees;
}
}
class Encapsulation
{
public static void main(String args[])
{
[Link]("Starting EmployeeCount...");
EmployeeCount employeeCount = new EmployeeCount ();
employeeCount. setNoOfEmployees (12003);
[Link]("NoOfEmployees = " + employeeCount.
getNoOfEmployees ());
}
}
Takeaway from above example:
The application using an Object of this class EmployeeCount will not able
to get the NoOfEmployees directly.
Setting and getting the value of the field NoOfEmployees is done with the
help of Getter and setter method as shown below.
Inheritance
The process by which one class acquires the properties and functionalities
of another class. Inheritance provides the idea of reusability of code and
each sub class defines only those features that are unique to it.
class Teacher {
private String name;
private double salary;
private String subject;
public Teacher (String tname) {
name = tname;
}
public String getName() {
return name;
}
private double getSalary() {
return salary;
}
private String getSubject() {
return subject;
}
}
Class: OfficeStaff
class OfficeStaff{
private String name;
private double salary;
private String dept;
public OfficeStaff (String sname) {
name = sname;
}
public String getName() {
return name;
}
private double getSalary() {
return salary;
}
private String getDept () {
return dept;
}
}
Points:
1) Both the classes share few common properties and methods. Thus
repetition of code.
2) Creating a class which contains the common methods and properties.
3) The classes Teacher and OfficeStaff can inherit the all the common
properties and methods from below Employee class
class Employee{
private String name;
private double salary;
public Employee(String ename){
name=ename;
}
public String getName(){
return name;
}
private double getSalary(){
return salary;
}
}
4) Add individual methods and properties to it Once we have created a
super class that defines the attributes common to a set of objects, it can
be used to create any number of more specific subclasses
5) Any similar classes like Engineer, Principal can be generated as
subclasses from the Employee class.
6) The parent class is termed super class and the inherited class is the sub
class
7) A sub class is the specialized version of a super class – It inherits all of
the instance variables and methods defined by the super class and adds
its own, unique elements.
8) Although a sub class includes all of the members of its super class it
can not access those members of the super class that have been declared
as private.
9) A reference variable of a super class can be assigned to a reference to
any sub class derived from that super class
i.e. Employee emp = new Teacher();
Note: Multi-level inheritance is allowed in Java but not multiple
inheritance
Types of Inheritance
Multilevel Inheritance
Multilevel inheritance refers to a mechanism in OO technology where
one can inherit from a derived class, thereby making this derived class the
base class for the new class.
Multiple Inheritance
“Multiple Inheritance” refers to the concept of one class inheriting from
more than one base class. The inheritance we learnt earlier had the
concept of one base class or parent. The problem with “multiple
inheritance” is that the derived class will have to manage the dependency
on two base classes.
Note 1: Multiple Inheritance is very rarely used in software projects.
Using Multiple inheritance often leads to problems in the hierarchy. This
results in unwanted complexity when further extending the class.
Note 2: Most of the new OO languages like Small Talk, Java, C# do not
support Multiple inheritance. Multiple Inheritance is supported in C++.
Polymorphism
Interfaces
Abstract Classes
Abstract Classes
Outlines the behavior but not necessarily implements all of its
behavior. Also known as Abstract Base Class.
Provides outline for behavior by means of method (abstract
methods) signatures without an implementation.
Note 1: There can be some scenarios where it is difficult to implement all
the methods in the base class. In such scenarios one can define the base
class as an abstract class which signifies that this base class is a special
kind of class which is not complete on its own.
A class derived from the abstract base class must implement those
member functions which are not implemented in the abstract class.
Note 2: Abstract Class cannot be instantiated.
To use an abstract class one has to first derive another class from this
abstract class using inheritance and then provide the implementation for
the abstract methods.
Note 3: If a derived class does not implement all the abstract methods
(unimplemented methods), then the derived class is also abstract in
nature and cannot be instantiated.
Example of Abstract class and Abstract Method:
abstract class Costume {
abstract public void Stitch();
public void setColour (){
//code to set colour
}
}
Here the class which inherits abstract class Costume can implement the
abstract method Stitch depending upon what kind of Costume it is.
What is a Constructor
1) A method with the same name as class name used for the purpose of
creating an object in a valid state
2) It does not return a value not even void
3) It may or may not have parameters (arguments)
4) A class contains one or more constructors for making new objects of
that class
5) If (and only if) the programmer does not write a constructor, Java
provides a default constructor with no arguments.
The default constructor sets instance variables as:
numeric types are set to zero
boolean variables are set to false
char variables are set to ‘’
object variables are set to null.
When a constructor executes, before executing its own code:
It implicitly call the default constructor of it’s super class Or can make this
constructor call explicitly, with super(…);
A constructor for a class can call another constructor for the same class by
putting this(…); as the first thing in the constructor. This allows you to
avoid repeating code.