
Java is an object oriented programming language developed by James Gosling at Sun Microsystems. Initially the language was known as oak, which later turned to name "JAVA".
It is used on varieties of devices like Desktop PCs, Mobile Devices, Televisions, Setup Boxes, Disc Players, etc.
Class
-> A blueprint to create an object
-> A template to represent a collection of objects
Object
-> Basic unit of object oriented programming which bundles data (properties) and functions that operate on that data.
-> An instance of a class
Data Encapsulation
-> Combining properties and methods together as a single unit is called encapsulation.
Data Abstraction
-> An act of taking essential details only and eliminating background details which are of no interest.
Polymorphism
-> An ability to take more than one form
Inheritance
-> Acquiring properties and methods from another class is called inheritance
Data hiding
-> Protecting data (properties) available inside a class from outside world
Object Oriented
-> Software is divided into small parts called objects
-> Includes object oriented concepts
–Class
–Object
–Encapsulation
–Data Abstraction
–Polymorphism
–Inheritance
–Data hiding
Platform Independent
-> Java code is compiled by the compiler and converted into bytecode
-> This bytecode is a platform independent code because it can be run on multiple platforms i.e. Write Once and Run Anywhere(WORA)
-> Java code can be run on multiple platforms e.g. Windows, Linux, Sun Solaris, Mac/OS etc.
Secure
-> Java doesn’t support pointers
-> Java programs runs on its own runtime environment
Robust
-> Java has exception handling mechanism
-> Java uses strong memory management features like garbage collection
Multithreaded
-> A thread is a unit of a program which can be executed independently
-> Java programs can deal with many tasks by running multiple threads in parallel.
Simple
-> Syntax derived from c/c++
-> Easy to learn
Try Yourself...
1. Write a java program to print your name and address.
Java vs C++
Java does not support pointer, while C++ supports pointer
No global data or functions in Java. Everything must be in a class, while in C++ global data and functions are available
Java does not support operator overloading, while C++ supports operator overloading
Java has built in support for multithreading, while C++ has no built in support for multithreading
Java generates bytecode which is platform independent, while C++ generates object code which may not run on different platforms
In Java member functions are defined within a class, while in C++ member functions can be defined either within the class or outside the class
Java does not support multiple inheritance, while C++ does
Java does not support preprocessor directives (for e.g. macro), while C++ supports preprocessor directives
Default arguments are not supported in Java, while C++ supports default arguments
Java has built-in support for documentation, while C++ has no support for documentation
Java does not have destructors. It supports garbage collection, while C++ uses destructors for removing objects
Token
Smallest individual unit in a program is called token.
1. Keywords
- Keywords are words reserved by Java for its own use
- For e.g. int, switch, abstract
2. Identifiers
- Identifiers are words used to identify things, such as variables, objects, classes, methods, etc.
3. Literals
- Java literals are constant values to be stored in variables.
# Integer literals
Decimal (25)
Octal (052)
Hexadecimal (0x2A3)
# Floating literals
float (2.342f)
double (7.2345719812d)
# Character literals (‘a’)
# String literals (“This is a String”)
# Boolean literals (true, false)
4. Operators
Operators are special symbols used to perform specific operations and generate a result
–Arithmetic operators
–Relational operators
–Logical operators
–Logical operator
–Ternary operator
5. Special Characters
, (comma)
{}
[]
…
Variables
Variable hold different values during the execution of a program
Declaration of a variable
datatype variable[=value], variable[=value]
For e.g.: int x, y=5;
Data types
Integers
–byte
–short
–int
–long
Floating point numbers
–float
–double
char
boolean
Try Yourself...
1. Write a JAVA program to calculate distance from the following equation.
d = ut + ½ at2
2. Write a JAVA program to calculate temperature value in Fahrenheit from given value in Celsius.
C = (F - 32) / 1.8
Type Conversion
1. Automatic Promotion
Java automatically converts variables or literals of lower precision type to a higher precision type during evaluation of expression or during assignment. This is known as automatic promotion.
Example1:
byte b1 = 50;
Example2:
char ch=‘a’;
int result = 100 / ch
2. Type Casting
There are situations where a higher precision type is converted to lower a lower precision. It is called type casting
Syntax: type variable = (type) expression
For e.g.:
double x = 317.2458;
int c = (int) x;
Operator Precedence
It specifies the order of evaluation of an expression with respect to operator priority.
if else statement
if(conditional expression)
{
statements;
}
else
{
statements;
}
For e.g.
if(marks >= 40)
{
result = “Pass”;
}
else
{
result = “Fail”;
}
if else if ladder
if(condition1)
{
statements;
}
else if(condition2)
{
statements;
}
else if(condition3)
{
statements;
}
.
.
else
{
statements;
}
Try Yourself...
1. Write a JAVA program to check whether a given character is vowel or not.
2. Write a JAVA program to check whether a given number is odd or even.
3. Calculate total and average marks of a student having seven subjects. Also calculate grade based on the following criteria:
Avg < 40% – Fail
< 50% – C
< 60% – B
< 85% – A
>= 85% – A+
4. Write a program to calculate roots of the equation ax2 + bx + c = 0
switch case
switch(expression)
{
case val1:
statements;
break;
case val2:
statements;
break;
case val3:
statements;
break;
.
.
default:
statements;
break;
}
Try Yourself...
1. Write a JAVA program which accepts a number between 1 and 5 as input and shows appropriate message for input number as given below:
For 1 - Hey buddy! Welcome.
2 - Good Morning Dear...
3 - You are super cool!!!
4 - Vola!, You are a genius.
5 - Have a nice time folk..
while loop
while(expression)
{
statements;
}
Try Yourself...
1. Write a JAVA program to calculate the following series.
x + x^2 + x^3 + x^4 + x^5 + … + x^n
do while loop
do
{
statements;
} while(expression);
Try Yourself...
1. Write a JAVA program to calculate factorial of a given number using do..while loop.
for loop
for(initialization; condition; increment/decrement)
{
statements;
}
Try Yourself...
1. Write a JAVA program to calculate the following series.
SinX = X – (X^3/3!) + (X^5/5!)– … (X^n/n!)
Array
An array is a collection of data elements of liked-type.
Types of Array
One dimensional array
Multi dimensional array
One dimensional array
data_type arrayname[] = new data_type[size]
int a[] = new int[5];
Multi dimensional array
data_type arrayname[][] = new data_type[row_size][col_size]
int a[][] = new int[3][4];
Try Yourself...
1. Write a java program to replace an element of given position in an array with new element.
(Take both position and new element from user)
2. Write a java program to find maximum and minimum values from a set of numbers.
Try Yourself...
1. Write a java program to calculate Multiplication of two given m x n matrices
Class
--> Basic building block of object oriented programming
--> It contains data and methods that manipulate that data.
Objects are instances of a Class
Defining a Class
class classname
{
visibility data-type variable1;
visibility data-type variable2;
…
visibility return-type method-name1(param-list)
{
method body;
}
visibility return-type method-name2(param-list)
{
method body;
}
}
Example
class Rectangle
{
private int length, breadth;
public void setvalues(int l, int b)
{
length=l;
breadth=b;
}
…
}
Object
--> A java object is one instance of a class.
--> The new operator is used to create an object, which returns an object reference.
Creating an Object
--> class-name obj-name = new class-name()
--> E.g. Rectangle r1 = new Rectangle();
Accessing Object Members
--> obj-name.member
--> For e.g. r1.setvalues(10,20);
Try Yourself...
1. Define a class to represent a bank account. Include constructors and the following members:
Data Members
1. Name of depositor
2. Account Number
3. Type of Account
4. Balance Amount
Member Functions
1. To deposit an amount
2. To withdraw an amount after checking minimum balance of Rs. 500
3. To display name and balance
Develop a menu driven java program to test the class.
2. Write a class to represent a student having seven subjects. The class should contain functions to calculate percentage and display grade with student name.
Try Yourself...
1. Write a class to represent a vector (a series of float values). Include member functions to perform the following tasks:
(a) To create the vector
(b) To modify the value of a given element
(c) To multiply vector by a scalar value
(d) To display the vector in the form (10, 20, 30, … )
Try Yourself...
1. Write a time class containing three integer values variables describing hours, minutes and seconds. Include necessary member functions. Also include a member function that adds two different time objects and returns the result as an object. Write a class with main () function to test this class.
2. Write a class to represent a two dimensional point. Include necessary member functions. Also include a function to calculate distance between two points whose objects are passed as argument. Write main to test the class.
Constructor
--> A constructor is a special member method which is called when object is created.
--> It is used to initialize instance variables (data members) of object.
Creating Constructor
The name of the constructor shall be the same as the name of the class itself.
class classname {
instance variables;
classname(parameter-list1)
{ ... }
classname(parameter-list2)
{ ... }...
}
Try Yourself...
1. Include all necessary constructors to time class in earlier example.
2. Include default and parameterized constructor for bank account class example.
3. Include all necessary constructors for Vector class.
Try Yourself...
1. Write a program that contains three different functions named area to calculate area of triangle, circle and rectangle with appropriate parameters. Test all functions from main.
Garbage Collection
--> Garbage collection is an automatic process of removing unused or unreferenced objects from memory and thus improving performance of the program.
--> For each object being removed using garbage collection, finalized() method available within class of the removing object is called before destroting the object. We may put code in it to release external resources occupied by object.
finalize() Method
class classname {
...
...
public void finalize()
{
...
code to be executed before object destruction
...
}
}
Inheritance
Acquiring properties and methods from another class is called inheritance.
Implementing Inheritance
class subclass extends superclass
{
…
}
Try Yourself...
1. Write a class with necessary methods and a method to find area of a rectangle. Create a subclass Cuboid with necessary members and methods. Calculate volume of Cuboid.
2. Write a class Person with appropriate data members and methods. Derive a class Employee from it. Include method to calculate Net Salary of an employee :
Net Salary = Basic Salary + DA + HRA + TA – IT
DA – 15% of Basic Salary
HRA – 20% of Basic Salary
TA – Fixed Value
IT – 10% of (Basic Salary+DA+HRA+TA)
3. Create a class account that stores customer name, account number and balance. From this derive the classes current account and savings account to make them more specific to their requirements. Current account maintains minimum balance of Rs. 1000, whereas savings account maintains minimum balance of Rs. 500. The interest rates for current and savings accounts are 5% and 12% respectively. Include necessary member function in these classes to manage the accounts. Write main to test these classes.
final Class
--> Can not be inherited
final Method
--> Can not be overridden
final Variables
--> final variables are constant
--> final variable must be initialized
final double PI = 3.14;
static Variable
--> A variable declared as static is shared commonly among all objects of that class.
class Complex {
int real, imaginary;
static int count = 1;
…
…
}
static Methods
--> Methods declared as static can be called by class name, thus no need to create object to call such methods
--> Static methods can access only other static members of class.
--> It can not use this or super inside the method.
Declaration Syntax
class Complex {
int real, imaginary;
static int count = 1;
…
static void showcount()
{
…
}
}
Calling a static method
--> classname.method(args)
Try Yourself...
1. Write a class with static methods, one returns maximum value of three given numbers and the other returns minimum value of the given three numbers. Write another class with main which calls these static methods to find maximum and minimum values from given two sets of three values.
--> Methods defined without body are called abstract methods
--> Class containing at least one abstract method is called abstract class
Syntax
abstract class classname
{
…
abstract returntype methodname(args);
…
}
Try Yourself...
1. Write an abstract class with an abstract method void Special(int n). Create a subclass of this class and implement the Special method that finds numbers that are perfect squares from 1 up to n.
2. Create an abstract class Product that stores product id, manufacturer name and base price. Include related methods and an abstract method to compute sale price. Derive classes MP3Player and TV from Product. Mp3 player is commissioned by 20% and TV by 15%. Also include necessary constructors and member methods. Write main to test the classes.
Interface
--> Interfaces contain methods without body
--> It cannot have instance variables but can contain final variables
Declaring an Interface
modifier interface ifname
{
final data-type var1 = val1;
…
modifier returntype methodname(args);
…
}
Example
interface Calculate
{
final double PI = 3.14;
double Area();
}
Implementing an Interface
--> After an interface is declared, all methods of interface are required to be implemented in another class.
Syntax
modifier class classname [extends superclass] implements inf1, inf2, …, infn
{
methods with body
}
Try Yourself...
1. Write an interface called Numbers, with a method int Process(int x,int y). Write a class called Sum, in which the method Process finds the sum of two numbers and returns an int value. Write another class called Average, in which the Process method finds the average of the two numbers and returns an int.
2. Write an interface called Exam with a methodPass(int mark) that returns a boolean. Write another interface called Classify with a method Division(int average) which returns a string. Write a class called Result which implements both Exam and Classify. The Pass method should return true if the mark is greater than or equal to 50 else false. The Division method must return “FIRST” when the parameter average is 60 or more, “SECOND” when average is 50 or more but below 60, “NO DIVISION” when average is less than 50.
Java Datatypes
- byte
- short
- int
- long
- float
- double
- char
What is wrapper types?
--> Java provides object wrappers for these basic data types, which helps to convert from simple types to the corresponding objects
--> It also helps in converting strings with digits to numeric types
Methods defined in subclass of Number
byte byteValue()
short shortValue()
int intValue()
long longValue()
float floatValue()
double doubleValue()
String toString()
What is Package?
A package is a namespace that organizes a set of related classes and interfaces. Conceptually you can think of packages as being similar to different folders on your computer.
Try Yourself...
1. Create a package org.shapes and add classes to represent a line and rectangle with necessary members. Create another package org.test and add a program to test line and rectangle class in it.
2. Create a package library mylib.maths and add class with functions to calculate factorial of a give number, to check weather a given number is prime or not and a function to check weather a given number is palindrome or not. Add this library to another project and test all functions.
3. Create a package org.pizza and add classes to create a pizza menu with necessary members. Create another package org.order to order pizza form the menu created.
What is Exception?
An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally, which is not recommended, therefore, these exceptions are to be handled.
try...catch Mechanism
try
{
statements that may give exceptions
}
catch(ExceptionType1 e1)
{
statements to handle Exception Type1
}
catch(ExceptionType2 e2)
{
statements to handle Exception Type2
}
…
finally
{
statements to be executed whether an exception occurs or not
}
Try Yourself...
1. Compute the expression f = x / (x2 – y2) for different values of x = 1.0 to 5.0 in steps of 0.5 and y = 0 to 4.0 in steps of 1. Write a Java program to compute the values of f by including an appropriate exception handling block when x = y
Try Yourself...
1. Write a program to sort the array of n integers in descending order. Include a try block to locate various exceptions related to array and catch them.
Try Yourself...
1. Write a java program that accepts employee basic details. Create and throw NotEligibleToVote exception if employee age is less than 18.
Checked Exceptions
--> Certain exceptions are identified by the compiler at the time of compilation itself.
--> Such exceptions are called checked exceptions
Some Checked Exceptions
- ClassNotFoundException
- CloneNotSupportedException
- IllegalAccessException
- InterruptedException
- NoSuchMethodException
Some Unchecked Exceptions
- ArithmeticException
- ArrayIndexOutOfBoundsException
- IllegalArgumentException
- NegativeArraySizeException
- NullPointerException
Try Yourself...
1. Create a class Quadratic to represent equation ax2 + bx + c with appropriate set method. Create a method delta() which calculates value of b2 – 4ac. Create a method root() which calculates root of the quadratic equation. This method should throw NoRealRootExistException in case delta() method returns negative value in the root calculation. The root() method should not handle the exception and broadcast it to be handled by its user. Write main() to test the class.
2. Write a class called MarkProcess to process the marks. A mark list containing register number and marks for subjects are given. Obtain the register number and marks as input. If marks are <0, user defined exception IllegalMarkException is thrown and handled with the message "Illegal Mark". For all valid marks, the candidate will be declared as "PASS" if the marks are>=40. Otherwise it will be declared as Fail. In MarkProcess class write a validation(int mark) method which is used to call the exception. Write another method result() which will declare the result. Write a class containing main method that will create an object of type MarkProcess and call the methods in it to declare the result.
java.util Package Classes
--> java.util package contains classes related to various collections, calander and time, and other miscellaneous classes.
java.util.ArrayDeque
--> This class provides resizable-array and implements the Deque interface
--> Concurrency not supported
--> Null elements are not allowed
java.util.ArrayList
--> This class also provides resizable-array and implements the List interface
--> Null elements are not allowed
java.util.Arrays
--> This class contains various methods for manipulating arrays (such as sorting and searching)
--> The methods in this class throw a NullPointerException if the specified array reference is null
java.util.HashTable
--> This class implements a hashtable, which maps keys to values
--> In this any non-null object can be used as a key or as a value
What is Multithreading?
--> A thread is a unit of a program which can be executed independently
--> Java programs can deal with many tasks by running multiple threads in parallel.
Try Yourself...
1. Write a Java program to compute first 10 prime numbers. Also compute the first 20 Fibonacci numbers. Create two threads to compute each one of them. Execute both threads to observe the output.
What is thread priority?
--> Threads can be assigned priorities in form of numeric values ranging from 1 to 10, where 1 indicates lowest priority value and 10 indicates highest priority value
--> Threads with higher priority value is given higher preference by CPU compared to threads with lower priority values
How to assign priority value?
--> Threadobj.setPriority(int value)
--> For e.g. sumthread.setPriority(8);
Predefined priority values
--> Thread.MIN_PRIORITY (with value 1)
--> Thread.NORM_PRIORITY (with value 5)
--> Thread.MAX_PRIORITY (with value 10)
Try Yourself...
1. In previous exercise of creating prime number and Fibonacci number threads, set the priority of thread that computes Fibonacci numbers to 8 and the other to 6. Observe the output on executing both threads.
Try Yourself...
1. Write a class that contains a method to compute Sin(x) series. Create four threads to calculate value of Sin(x) with different values of x and for different number of terms of series using same object. Display each term calculated from series and the final result. Make sure that only one thread is calculating the series at a time.
Try Yourself...
1. With respect to prime and Fibonacci threads created earlier, After calculating 10 Fibonacci numbers make that thread to sleep and take up prime number computation.
Try Yourself...
1. With respect to prime and Fibonacci threads created earlier, After computing 10 prime numbers continue the Fibonacci number computing. Observe the output.
Learn Java programming in easy steps with example demonstrations. The course starts with fundamental concepts of object oriented programming. Then it teaches basic programming in Java followed by object oriented programming concepts. Having learned object oriented programming, It moves ahead to robust programming with exception handling and teaches concurrent programming using multithreading.
Moving to advanced level graphical applications with swing library, event handling, applets and file handling are discussed.