[Go to site: main page, start]

0% found this document useful (0 votes)
3 views48 pages

Introduction To Java Programming

The document provides an introduction to Java programming, detailing its history, features, and basic concepts such as object-oriented programming, platform independence, and memory management. It includes tutorials on writing, compiling, and executing Java programs, along with examples of loops and error handling. Additionally, it explains the Java Virtual Machine (JVM) and the structure of Java source code.

Uploaded by

hemali kotak
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views48 pages

Introduction To Java Programming

The document provides an introduction to Java programming, detailing its history, features, and basic concepts such as object-oriented programming, platform independence, and memory management. It includes tutorials on writing, compiling, and executing Java programs, along with examples of loops and error handling. Additionally, it explains the Java Virtual Machine (JVM) and the structure of Java source code.

Uploaded by

hemali kotak
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

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.

Main Features of JAVA


Java is a platform independent language

To understand the meaning of platform independent, we must need to understand the


meaning of platform first. A platform is a pre-existing environment in which a program runs,
obeying its constraints, and making use of its facilities.
Lets back to the point. During compilation, the compiler converts java program to its byte
code. This byte code can run on any platform such as Windows, Linux, Mac/OS etc. Which
means a program that is compiled on windows can run on Linux and vice-versa. This is why
java is known as platform independent language.

Java is an Object Oriented language

Object oriented programming is a way of organizing programs as collection of objects, each


of which represents an instance of a class.

4 main concepts of Object Oriented programming are:

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

Using java programming language we can create distributed applications. RMI(Remote


Method Invocation) and EJB(Enterprise Java Beans) are used for creating distributed
applications in java. In simple words: The java programs can be distributed on more than one
systems that are connected to each other using internet connection. Objects on one JVM (java
virtual machine) can execute procedures on a remote JVM.

Multithreading

Java supports multithreading. It enables a program to perform several tasks simultaneously.

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.

Java Tutorial – Compilation and Execution


of First Java Program
Java Tutorials

To create a java code an editor such as notepad, text pad or an IDE like eclipse can be used.

Sample Java Code:


public class FirstJavaProgram {
public static void main(String[] args){
[Link]("This is my first program in java");
}//End of main
}//End of FirstJavaProgram Class

Output: This is my first program in java

 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

Step1: Save the source file as [Link].


Step2: Open command prompt and navigate to the directory where you have stored the file.
Step 3: To compile, type javac [Link] and press Enter.
Step 4: On successful compilation, you will see the command prompt and
[Link] file in the same folder where [Link] is stored. This is the
byte code of the program.
Step 5: To execute, type java FirstJavaProgram. Do not type the extension while executing.
Step 6: See the output “This is my first program in java” displayed on the console.

Common programming Errors in Java

The following are the general programming errors and the solution for them while running on
windows machine.

1) ‘javac’ is not recognized as an internal or external command, operable program or


batch file – This means that the operating system cannot find the compiler – javac. In order
to resolve this the PATH variable has to be set.
2) Exception in thread “main”[Link]: FirstJavaProgram –
This error means that java cannot find your compiled byte code, [Link]. If the
class file is present in directory other than the directory where java file is stored, then the
CLASSPATH must be set pointing to the directory that contains compiled class files.

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]();
}
}

Output: Hello World


Interpreting the code

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

The programming structure

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

Java Tutorial – JVM (Java virtual


Machine)
Java Tutorials
1) Class loader accepts class files
2) Compilation creates class files
3) The interim memory is required during execution
4) It consists of heaps, stacks and registers to store data
5) JRE has native methods and libraries
6) JVM runs two main threads
a) demon
b) Non-demon threads

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

Java Source code

1) It essentially consists of a main() method


2) This method is public and thus can be called by any object
3) This method is also static and so can be called without instantiating the object of the class
4) It does not return any value
5) The controlling class of every Java application usually contain a main method
6) This can be avoided to allow the class to be tested in a stand-alone mode.
7) Other methods can subsequently be called in main()

For loop in Java with example


Java Examples

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.

What is For loop?

It executes a block of statements repeatedly until the specified condition returns false.

Syntax of for loop:


for (initialization; condition; increment/decrement) {
statement(s) //block of statements
}

Mind the semicolon (;) after initialization and condition in the above syntax.

Initialization expression executes only once during the beginning of loop


Condition(Boolean Expression) gets evaluated each time the loop iterates. Loop executes
the block of statement repeatedly until this condition returns false.
Increment/Decrement It executes after each iteration of loop.

Confused??
Don’t worry let see an example to understand it better.

For loop example:


class ForLoopExample {
public static void main(String args[]){
for(int i=10; i>1; i--){
[Link]("The value of i is: "+i);
}
}
}

The output of this program is:

The value of i is: 10


The value of i is: 9
The value of i is: 8
The value of i is: 7
The value of i is: 6
The value of i is: 5
The value of i is: 4
The value of i is: 3
The value of i is: 2

In the above program:


int i=1 is initialization expression
i>1 is condition(Boolean expression)
i– Decrement operation

Flow diagram of for loop


Infinite for loop: The importance of Boolean expression and
increment/decrement operation co-ordination:
class ForLoopExample2 {
public static void main(String args[]){
for(int i=1; i>1; i++){
[Link]("The value of i is: "+i);
}
}
}

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.

Here is another example of infinite for loop:

// infinite loop
for ( ; ; ) {
// statement(s)
}

For loop example to iterate an array:

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

While loop in Java with examples


Java Examples

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.

What is while loop?


Like for loop, It also executes a block of statements repeatedly until the condition(Boolean
expression) returns false.

Syntax of while loop


while (Boolean expression) {
statement(s) //block of statements
}

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.

Are you confused??


Don’t worry we will see the flow diagrams and example. That would make you comfortable.

While loop example


class WhileLoopExample {
public static void main(String args[]){
int i=10
while(i>1){
[Link](i);
i--;
}
}
}
The output of this program is:
10
9
8
7
6
5
4
3
2

Did you understand how we get that output?


If not refer the below flow diagram.

While loop flow diagram

Infinite while loop


class WhileLoopExample2 {
public static void main(String args[]){
int i=10
while(i>1)
{
[Link](i);
i++;
}
}
}

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.

Here is another example of infinite while loop:

while (true){
statement(s);
}

While loop example to iterate an array

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

do-while loop in Java with example


Java Examples

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

Introduction to do-while loop

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.

Syntax of while loop:


do{
statement(s) //block of statements
}while (Boolean expression);

do-while loop example


class DoWhileLoopExample {
public static void main(String args[]){
int i=10;
do{
[Link](i);
i--;
}while(i>1);
}
}

The output of this program is:


10
9
8
7
6
5
4
3
2

do-while loop example program to iterate an array

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

Program 1: Reverse a number using while Loop

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;
}

[Link]("Reverse of input number is: "+reversenum);


}
}

Output:

Input your number and press enter:


145689
Reverse of input number is: 986541

Program 2: Reverse a number using for Loop


import [Link];
class ForLoopReverseDemo
{
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]();
/* for loop: No initialization part as num is already
* initialized and no increment/decrement part as logic
* num = num/10 already decrements the value of num
*/
for( ;num != 0; )
{
reversenum = reversenum * 10;
reversenum = reversenum + num%10;
num = num/10;
}

[Link]("Reverse of specified number is: "+reversenum);


}
}
Output:

Input your number and press enter:


56789111
Reverse of specified number is: 11198765

Program 3: Reverse a number using recursion


import [Link];
class RecursionReverseDemo
{
//A method for reverse
public static void reverseMethod(int number) {
if (number < 10) {
[Link](number);
return;
}
else {
[Link](number % 10);
//Method is calling itself: recursion
reverseMethod(number/10);
}
}
public static void main(String args[])
{
int num=0;
[Link]("Input your number and press enter: ");
Scanner in = new Scanner([Link]);
num = [Link]();
[Link]("Reverse of the input number is:");
reverseMethod(num);
[Link]();
}
}

Output:

Input your number and press enter:


5678901
Reverse of the input number is:1098765

Example: Reverse an already initialized number


In all the above programs we are prompting user for the input number, however if do not
want the user interaction part and want to reverse an initialized number then this is how you
can do it.

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:

Reverse of specified number is: 987654321

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:

Enter the radius: 1


The area of circle is: 3.141592653589793
The circumference of the circle is:6.283185307179586

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:

The area of circle is: 28.274333882308138


The circumference of the circle is:18.84955592153876

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]);

[Link]("Enter the width of the Triangle:");


double base = [Link]();

[Link]("Enter the height of the Triangle:");


double height = [Link]();

//Area = (width*height)/2
double area = (base* height)/2;
[Link]("Area of Triangle is: " + area);
}
}

Output:

Enter the width of the Triangle:


2
Enter the height of the Triangle:
2
Area of Triangle is: 2.0
Program 2:

/**
* @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:

Area of Triangle is: 1105.0

Java program to sum the elements of an


array
Java Examples

In this tutorial we will see how to sum up all the elements of an array.

Program 1: No user interaction

/**
* @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:

Sum of array elements is:160

Program 2: User enters the array’s elements

/**
* @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:

Enter the elements:


1
2
3
4
5
6
7
8
9
10
Sum of array elements is:55

Java program to check prime number


Java Examples

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:

Enter a number for check:


19
19 is Prime Number

Output 2:

Enter a number for check:


6
6 is not Prime Number

Java Program to check Even or Odd


number
Java Examples
import [Link];

class CheckEvenOdd
{
public static void main(String args[])
{
int num;
[Link]("Enter an Integer number:");

//The input provided by user is stored in num


Scanner input = new Scanner([Link]);
num = [Link]();

/* If number is divisible by 2 then it's an even number


* else odd number*/
if ( num % 2 == 0 )
[Link]("Entered number is even");
else
[Link]("Entered number is odd");
}
}

Output 1:

Enter an Integer number:


78
Entered number is even

Output 2:

Enter an Integer number:


77
Entered number is odd

Java program for linear search – Example


Java Examples

Example Program:

This program uses linear search algorithm to find out a number among all other numbers
entered by user.

/* Program: Linear Search Example


* Written by: Chaitanya from [Link]
* Input: Number of elements, element's values, value to be searched
* Output:Position of the number input by user among other numbers*/
import [Link];
class LinearSearchExample
{
public static void main(String args[])
{
int counter, num, item, array[];
//To capture user input
Scanner input = new Scanner([Link]);
[Link]("Enter number of elements:");
num = [Link]();
//Creating array to store the all the numbers
array = new int[num];
[Link]("Enter " + num + " integers");
//Loop to store each numbers in array
for (counter = 0; counter < num; counter++)
array[counter] = [Link]();

[Link]("Enter the search value:");


item = [Link]();

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


{
if (array[counter] == item)
{
[Link](item+" is present at location "+(counter+1));
/*Item is found so to stop the search and to come out of the
* loop use break statement.*/
break;
}
}
if (counter == num)
[Link](item + " doesn't exist in array.");
}
}
Output 1:

Enter number of elements:


6
Enter 6 integers
22
33
45
1
3
99
Enter the search value:
45
45 is present at location 3

Output 2:

Enter number of elements:


4
Enter 4 integers
11
22
4
5
Enter the search value:
99
99 doesn't exist in array.

Java program to perform binary search –


Example
Java Examples

Example Program to perform binary search on a list of integer numbers

This program uses binary search algorithm to search an element in given list of elements.

/* Program: Binary Search Example


* Written by: Chaitanya from [Link]
* Input: Number of elements, element's values, value to be searched
* Output:Position of the number input by user among other numbers*/
import [Link];
class BinarySearchExample
{
public static void main(String args[])
{
int counter, num, item, array[], first, last, middle;
//To capture user input
Scanner input = new Scanner([Link]);
[Link]("Enter number of elements:");
num = [Link]();

//Creating array to store the all the numbers


array = new int[num];
[Link]("Enter " + num + " integers");
//Loop to store each numbers in array
for (counter = 0; counter < num; counter++)
array[counter] = [Link]();

[Link]("Enter the search value:");


item = [Link]();
first = 0;
last = num - 1;
middle = (first + last)/2;

while( first <= last )


{
if ( array[middle] < item )
first = middle + 1;
else if ( array[middle] == item )
{
[Link](item + " found at location " + (middle + 1) +
".");
break;
}
else
{
last = middle - 1;
}
middle = (first + last)/2;
}
if ( first > last )
[Link](item + " is not found.\n");
}
}

Output 1:

Enter number of elements:


7
Enter 7 integers
4
5
66
77
8
99
0
Enter the search value:
77
77 found at location 4.

Output 2:

Enter number of elements:


5
Enter 5 integers
12
3
77
890
23
Enter the search value:
99
99 is not found.

Java program to generate random number


– Example
Example Program to generate random numbers

In the below program, we are using the nextInt() method of Random class to serve our
purpose.

/* Program: Random number generator


* Written by: Chaitanya from [Link]
* Input: None
* Output:Random number between o and 200*/
import [Link].*;
class GenerateRandomNumber {
public static void main(String[] args) {
int counter;
Random rnum = new Random();
/* Below code would generate 5 random numbers
* between 0 and 200.
*/
[Link]("Random Numbers:");
[Link]("***************");
for (counter = 1; counter <= 5; counter++) {
[Link]([Link](200));
}
}
}

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];

public class Details {

public void countDupChars(String str){

//Create a HashMap
Map<Character, Integer> map = new HashMap<Character, Integer>();

//Convert the String to char array


char[] chars = [Link]();

/* logic: char are inserted as keys and their count


* as values. If map contains the char already then
* increase the value by 1
*/
for(Character ch:chars){
if([Link](ch)){
[Link](ch, [Link](ch)+1);
} else {
[Link](ch, 1);
}
}

//Obtaining set of keys


Set<Character> keys = [Link]();
/* Display count of chars if it is
* greater than 1. All duplicate chars would be
* having value greater than 1.
*/
for(Character ch:keys){
if([Link](ch) > 1){
[Link]("Char "+ch+" "+[Link](ch));
}
}
}

public static void main(String a[]){


Details obj = new Details();
[Link]("String: [Link]");
[Link]("-------------------------");
[Link]("[Link]");

[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

Java program for binary to


decimal conversion
JAVA EXAMPLES

There are two following ways to convert binary number to decimal


number:

1) Using [Link]() method of Integer class.


2) Do conversion by writing your own logic without using any predefined
methods.

Method 1: Binary to Decimal conversion


using [Link]() method

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

Method 2: Conversion without using


parseInt

public class Details {

public int BinaryToDecimal(int binaryNumber){

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;
}

public static void main(String args[]){


Details obj = new Details();
[Link]("110 --> "+[Link](110));
[Link]("1101 --> "+[Link](1101));
[Link]("100 --> "+[Link](100));
[Link]("110111 --> "+[Link](110111));
}
}
Output:
110 --> 6
1101 --> 13
100 --> 4
110111 --> 55

Java Program to get input from


user
JAVA EXAMPLES

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;

Scanner in = new Scanner([Link]);


//Get input String
[Link]("Enter a string: ");
str = [Link]();
[Link]("Input String is: "+str);

//Get input Integer


[Link]("Enter an integer: ");
num = [Link]();
[Link]("Input Integer is: "+num);

//Get input float number


[Link]("Enter a float number: ");
fnum = [Link]();
[Link]("Input Float number is: "+fnum);
}
}
Output:
Enter a string:
Chaitanya
Input String is: Chaitanya
Enter an integer:
27
Input Integer is: 27
Enter a float number:
12.56
Input Float number is: 12.56

OOPs concepts in Java


OOPS CONCEPT

OOPs Basics

1. Method overloading 2. Method overriding 3. Exception handling in method


overriding

4. Method overloading vs
5. Constructors 6. Constructor overloading
Overriding

8. Constructors in
7. private constructor 9. Constructor chaining
interfaces

10. Aggregation 11. Association 12. OOPs basics

13. Polymorphism in java 14. Types of polymorphism 15. Inheritance

16. Types of inheritance 17. Hybrid inheritance 18. Hierarchical inheritance

19. Multilevel inheritance 20. Multiple inheritance 21. Encapsulation

22. Static and dynamic binding in


23. Static class 24. Static methods
java

25. Static variables 26. Static import 27. Static constructor

29. Abstract class and


28. Inner classes 30. Interfaces in java
methods

31. Abstract class vs interface 32. Access modifiers 33. Packages in java

34. Final Keyword 35. Super keyword

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.

Limitations of Unstructured Programming


a) The data is global and code operates on it
b) As the size of code increases, maintenance is a problem
c) Does not have independent data for processing
d) The concept of local variables did not exist
e) Reusability of code was not supported
Assembly Language: Similar to machine language, but provides names
for numeric instructions present in the machine language, making it easy
for the programmer.
Machine language is the language which a Central Processing Unit
(CPU) of a computer understands and consists only of numbers.
2. Variables
Global Variables
a) The variables that are declared outside any function body.
b) These variables exist for the entire life-cycle of the program.
c) Global variables can be accessed from anywhere within the program.
Local Variables
a) The variables that are declared within a function body.
b) Their scope is limited to within the function body.
c) Local variables cannot be accessed outside the function body.
Object Oriented Programming
Object
Object: is a bundle of related variables and functions (also known
methods).
Objects share two characteristics: They have State and Behavior.
State: State is a well defined condition of an item. A state captures the
relevant aspects of an object
Behavior: Behavior is the observable effects of an operation or event,
Examples:
eg 1:
Object: House
State: Current Location, Color, Area of House etc
Behavior: Close/Open main door.
eg 2:
Object: – Car
State: Color, Make
Behavior: Climb Uphill, Accelerate, SlowDown etc
Note: Everything a software object knows (State) and can do (Behavior) is
represented by variables and methods (functions) in the object
respectively.
Characteristics of Objects:
1. Abstraction
2. Encapsulation
3. Message passing
Message passing
A single object by itself may not be very useful. An application contains
many objects. One object interacts with another object by invoking
methods (or functions) on that object. Through the interaction of objects,
programmers achieve a higher order of functionality which has complex
behavior.
One object invoking methods on another object is known as Message
passing.
It is also referred to as Method Invocation.
Class
A class is a prototype that defines the variables and the methods common
to all objects of a certain kind. Member Functions operate upon the
member variables of the class. An Object is created when a class in
instantiated.

How to create an Object?


An object is created when a class is instantiated
Declaring an Object of class :

ClassName Objectname;
Object definition is done by calling the class constructor

Constructor: A special member function which will be called


automatically to initialize the data member of a class whenever object is
instantiated.
Memory space is allocated only when a class is instantiated i.e. when an
object is created
Defining a variable :
E.g. GraduationCourse mycourse= new GraduationCourse();
Object Oriented Programming features:
Abstraction

The purpose of abstraction is to hide information that is not


relevant or rather show only relevant information and to simplify it
by comparing it to something similar in the real world.
Abstraction means “The process of forming of general and
relevant concept from more complex scenarios”.
Note 1: Abstraction is used to build complex systems.
Key to simplify a complex design into smaller, manageable parts
which then become the components of a bigger and complex
system.
The idea of hiding the complexity within a smaller/simple component of a
system.
Note 2: Abstraction is not a feature of Object oriented concepts alone.
Even in procedural language programming, abstraction can be achieved
to a limited extent by hiding complex internals through well formed
business logic and functions.

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.

1. Inheritance is a mechanism of defining a new class based on an existing


class.
2. Inheritance enables reuse of code. Inheritance also provides scope for
refinement of the existing class. Inheritance helps in specialization
3. The existing (or original) class is called the base class or super
class orparent class. The new class which inherits from the base class is
called the derived class or sub class or child class.
4. Inheritance implements the “Is-A” or “Kind Of/ Has-A” relationship.
Note : The biggest advantage of Inheritance is that, code in base class
need not be rewritten in the derived class.
The member variables and methods of the base class can be used in
thederived class as well.
Inheritance Example
Consider below two classes –
Class Teacher:

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

Polymorphism is a feature that allows one interface to be used for a


general class of actions. It’s an operation may exhibit different behavior in
different instances. The behavior depends on the types of data used in the
operation. It plays an important role in allowing objects having different
internal structures to share the same external interface. Polymorphism is
extensively used in implementing inheritance.
Types of Polymorphism
1) Static Polymorphism
2) Dynamic Polymorphism
Static Polymorphism:
Function Overloading – within same class more than one method
having same name but differing in signature.
Resolved during compilation time.
Return type is not part of method signature.
Dynamic Polymorphism
Function Overriding – keeping the signature and return type same,
method in the base class is redefined in the derived class.
Resolved during run time.
Which method to be invoked is decided by the object that the reference
points to and not by the type of the reference.
Overriding:
Redefining a super class method in a sub class is called method
overriding.
The method signature ie. method name, parameter list and return type
have to match exactly.
The overridden method can widen the accessibility but not narrow it, ie if
it is private in the base class, the child class can make it public but not
vice versa.
Overriding Examples:
Consider a Super Class Doctor and Subclass Surgeon. Class Doctor has a
method treatPatient(). Surgeon overrides treatPatient method ie gives a
new definition to the method.
Doctor doctorObj = new Doctor();
// Call the treatPatient method of Doctor class
[Link]()
Surgeon surgeonObj = new Surgeon();
// Call the treatPatient method of Surgeon class
[Link]()
Doctor obj = new Surgeon();
// calls Surgeon’s treatPatient method as the reference is pointing to
Surgeon
[Link]();
Method/Function Overloading:
Method Overloading refers to the practice of using the same name to
denote several different operations. Overloading can be done for both
functions as well as operators. Here we look at only Method overloading.
Declaration:
void SomeMethod (int value);
void SomeMethod (float value);
void SomeMethod (char value);
void SomeMethod (String* str);
void SomeMethod (char* str);
All the five methods are called ‘SomeMethod ’. All the methods have the
same name, but different signatures.

The concept of the same function name with different types of


parameters being passed is called Function Overloading.
1) In Overloading we can reuse the same method name by changing the
arguments.
2) Overloaded methods- Must and Must Not Facts:
 The Overloaded method must have different argument lists,
 Can have different return types but in that case it is mandatory to have
different argument list.
 Can have different access modifiers and
 Can throw different exceptions
3) Methods can be overloaded in the same as well as the sub classes.

Q: What determines which overridden method is used at runtime?


A: Object type
Q: What determines which overloaded method will be used at compile
time?
A: Reference type determines.
Operator overloading refers to the operators like ‘+’ being used for
different purposes based on the data type on either side of the operator.
Combined example for Inheritance & Polymorphism
abstract public class Employee {
private String name;
public Employee(String ename) {
name = ename;
}
public String getName() {
return new name;
}
private void setName(String name) {
[Link] = new String(name);
}
abstract public double pay();
public String toString() {
return "name is" + name;
}
}
public class Salaried extends Employee {
double salary;
public Salaried(String name, double s) {
super(name);
salary =s;
}
public void setSalary(double salary) {
[Link] = salary;
}
public double getSalary() {
return salary;
}
public double pay() {
return salary;
}
public String toString(){
return [Link]() + " (salary is " +salary+")";
}
}
IS-A & HAS-A Relationships
public class SuperClass { … }
public class SubClass1 extends SuperClass { //SubClass 1 code goes here }
public class SubClass2 extends SubClass1 { //SubClass2 Specific code goes
here }
HAS-A relationships are based on usage, rather than inheritance. In other
words, class A HAS-A B if code in class A has a reference to an instance of
class B.
For example, we can say the following,
A Car IS-A Vehicle. A Car HAS-A License. and the code looks like this:
public class Vehicle{ }
public class Car extends Vehicle{
private License myCarLicense;
}

Interfaces

As in the above example Teacher class contains the attributes and


methods of Employee as well as Musician.

1. Java does not support Multiple Inheritance


2. Interface is similar to an abstract class that contains only abstract methods
3. Declared with the keyword interface instead of the keyword class
4. Keyword implements is used to represent the interfaces implemented by the
class
Interface: Syntax
class ClassName extends Superclass implements Interface1, Interface2, ....
Example : class MusicTeacher extends Teacher implements Musician

All methods in an interface are implicitly public and


abstract.
The keyword abstract before each method is optional.
An interface may contain definitions of final variables.
A class may extend only one other class , but it
mayimplement any number of interfaces.
When a class implements an interface, it may implement
(define) some or all of the inherited abstract methods.
A class must itself be declared abstract if it inherits abstract
methods that it does not define.
An interface reference can point to objects of its
implementing classes.
Abstract method
1) A method that is declared but not defined
2) Declared with the keyword abstract
3) Example :
abstract public void playInstrument();
4) Has a header like any other method, but ends with a semicolon instead
of a method body
5) Used to put some kind of compulsion on the class who inherits from this
class. i.e., the class who inherits MUST provide the implementation of the
method else the subclass will also become abstract
6) The following cannot be marked with “abstract” modifier
 Constructors
 Static methods
 Private methods
 Methods marked with “final” modifier

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.

A Class do not inherit the constructors of a super class.


Generalization and Specialization:
In order to implement the concept of inheritance in an OO solution, one
has to first identify the similarities among different classes so as to come
up with the base class.
This process of identifying the similarities among different classes is
calledGeneralization.
The class which is identified after generalization is the base class. The
classes over which the generalization is made are the derived classes.

The classes over which the generalization is built are viewed


asSpecialization.
Generalization identifies the common attributes and behavior among
different entities whereas specialization identifies the distinct attributes
and their behavior which differentiate a derived class from the other
classes.
A Generalization–Specialization hierarchy is used to depict the
relationship between the generalized class and the corresponding
specialized classes.
Access Specifiers
Access specifiers in a class
An access specifier is a keyword in OO Programming languages, which
specify what access is permitted on a member.
There are three types of access specifiers:
public: Accessible to all. Other objects can also access this member
variable or function.
private: Not accessible by other objects. Private members can be
accessed only by the methods in the same class. Object accessible only
in Class in which they are declared.
protected: The scope of a protected variable is within the class which
declares it and in the class which inherits from the class (Scope is Class
and subclass)
Default: Scope is Package Level
Approach to Object Oriented Design:
Step 1. Identify all the classes (Nouns; Type of objects) in the
requirement specification,
Step 2. Identify the commonalities between all or small groups of classes
identified (generalization) if it is obvious. Do not force fit generalization
where it doesn’t make sense.
Step 3. In any given situation, start with the simplest object which can be
abstracted into individual classes
Step 4. Identify all the member variables and methods the class should
have
Step 5. Ensure that the class is fully independent of other classes and
contains all the attributes and methods necessary.
Step 6. Keep all the data members private or protected
Step 7. The methods in the class should completely abstract the
functionality
Step 8. The methods in the class should not be a force fit of procedural
code into a class
Step 9. Inherit and extend classes from the base classes ONLY IF the
situation has scope for it
Step 10. Define the relationships among the classes (“Has-A”, “Uses-A”)
Step 11. Keep the number of classes in your application under check (do
not create any unnecessary classes)

You might also like