Java Notes
Java Notes
Java was initially developed in 1991 named as “oak” but was renamed “Java” in 1995.
Originally designed for small, embedded systems in electronic appliances like set-top boxes.
The primary motivation was the need for a platform-independent language that could be used
to create software to be embedded in various consumer electronic devices.
Java programming language was originally developed by Sun Microsystems which was
initiated by James Gosling and released in 1995 as core component of Sun Microsystems' Java
platform (Java 1.0 [J2SE]).
It promised Write Once, Run Anywhere (WORA), providing no-cost run-times on popular
platforms.
Java 2, new versions had multiple configurations built for different types of platforms. J2EE
included technologies and APIs for enterprise applications typically run in server
environments, while J2ME featured APIs optimized for mobile applications.
The desktop version was renamed J2SE. In 2006, for marketing purposes, Sun renamed new
J2 versions as Java EE, Java ME, and Java SE, respectively.
On 13 November 2006, Sun released much of Java as free and open-source software (FOSS),
under the terms of the GNU General Public License (GPL).
On 8 May 2007, Sun finished the process, making all of Java's core code free and open-source,
aside from a small portion of code to which Sun did not hold the copyright.
What is Java?
Java is a programming language that:
Is exclusively object oriented
Has full GUI support
Has full network support
Is platform independent
Executes stand-alone or “on-demand” in web browser as applets
JDK, JRE, Byte code & JVM.
Compiler
(Javac.exe) Java
JVM
Java Packages
Application
(math,
Launcher
(java.exe), Runtime
AppletViewer, Libraries
etc..)
Development tools JRE
JDK
JAVAC Compiler
1. Simple
2. Secure
3. Portable
4. Object-oriented
5. Robust
6. Multithreaded
7. Architecture-natural
8. Interpreted
9. High performance
10. Distributed
11. Dynamic
Simple
o It’s simple because it contains many features of other languages like C and C++
o It also removed complexities like pointers, Storage classes, goto statement and multiple
Inheritance.
Secure
o Java is best known for its security. With Java, we can develop virus-free systems. Java is
secured because:
1. No explicit pointer
2. Java Programs run inside virtual machine sandbox
3. Bytecode Verifier
Portable
o Java is portable because it facilitates you to carry the java bytecode to any platform.
Object oriented
o Java is Object-oriented programming language. Everything in Java is an object.
Robust
o Robust simply means strong. Java is robust because:
1. It uses strong memory management.
2. There are lack of pointers that avoids security problem.
3. There is automatic garbage collection in java.
4. There is exception handling and type checking mechanism in java. All these points makes
java robust
Multithreaded
o A thread is like a separate program, executing concurrently.
o We can write Java programs that deal with many tasks at once by defining multiple threads.
o The main advantage of multi-threading is that it doesn't occupy memory for each thread.
o It shares a common memory area. Threads are important for multi-media, Web applications
etc…
Architecture-neutral
o Java is architecture neutral because there is no implementation dependent features e.g. size
of primitive types is fixed.
o Example : in c int occupy 2 byte for 32 bit OS and 4 bytes for 64 bit OS whereas in JAVA it
occupy 4 byte for int both in 32 bit and 64 bit OS.
Interpreted
o Java enables the creation of cross-platform programs by compiling into an intermediate
representation called Java bytecode.
o This code can be executed on any system that implements the Java Virtual Machine.
High-Performance
o Most previous attempts at cross-platform solutions have done so at the expense of
performance.
o As explained earlier, the Java bytecode was carefully designed so that it would be easy to
translate directly into native machine code for very high performance by using a just-in-time
compiler.
Dynamic
o Java programs carry with them substantial amounts of run-time type information that is used
to verify and resolve accesses to objects at run time.
o This makes it possible to dynamically link code in a safe and expedient manner.
Distributed
o Java is distributed because it facilitates us to create distributed applications in java.
o RMI and EJB are used for creating distributed applications.
o We may access files by calling the methods from any machine on the internet.
Platform Independent
o Java is a platform independent programming language, because when you install JDK in the
system then JVM is also installed automatically on the system.
o For every operating system separate JVM is available which is capable to read the .class file
or byte code.
o When we compile Java code then .class file is generated by java compiler (javac) these codes
are readable by the JVM and every operating system have its own JVM so JVM is platform
dependent but due to JVM java is platform independent.
1 Arithmetic Operators +, -, *, /, %
2 Relational Operators <, <=, >, >=, ==, !=
3 Logical Operators &&, ||, !
4 Assignment Operators =, +=, -=, *=, /=
5 Increment and Decrement Operators ++, --
6 Conditional Operator ?:
7 Bitwise Operators &, |, ^, <<, >>
Arithmetic Operator
An arithmetic operator performs basic mathematical calculations such as addition,
subtraction, multiplication, division etc. on numerical values (constants and variables).
Increment / Decrement Operators
o Increment and decrement operators are unary operators that add or subtract one,
to or from their operand.
o the increment operator ++ increases the value of a variable by 1, e.g. a++ means
a=a+1
o the decrement operator -- decreases the value of a variable by 1. e.g. a–– means
a=a–1
o If ++ operator is used as a prefix (++a) then the value of a is incremented by 1 first
then it returns the value.
o If ++ operator is used as a postfix (a++) then the value of a is returned first then it
increments value of a by 1.
Operator Description Example
Logical Operators
Logical operators are decision making operators.
They are used to combine two expressions and make decisions.
An expression containing logical operator returns either 0 or 1 depending upon whether
expression results false or true.
Operators Precedence and Associativity are two characteristics of operators that determine
the evaluation order of sub-expressions in absence of brackets.
Operator precedence determines which operation is performed first in an expression with
more than one operators with different precedence.
a=10 + 20 * 30 is calculated as 10 + (20 * 30) and not as (10 + 20) * 30 so answer is 610.
Operators Associativity is used when two operators of same precedence appear in an
expression. Associativity can be either Left to Right (L to R) or Right to Left (R to L).
E.g. a=100 / 10 * 10
If Left to Right means (100 / 10) * 10 then answer is 100
If Right to Left means 100 / (10 * 10) then answer is 1
Division (/) & Multiplication (*) are Left to Right associative so the answer is 100.
Explain short circuit operators.
Java provides two interesting Boolean operators not found in many other computer languages.
These are secondary versions of the Boolean AND and OR operators, and are known as
shortcircuit logical operators.
The OR operator results in true when A is true, no matter what B is. Similarly, the AND operator
results in false when A is false, no matter what B is. If you use the || and && forms, rather than
the | and & forms of these operators, Java will not bother to evaluate the right-hand operand
when the outcome of the expression can be determined by the left operand alone.
This is very useful when the right-hand operand depends on the value of the left one in order to
function properly. For example, the following code fragment shows how you can take advantage
of short-circuit logical evaluation to be sure that a division operation will be valid before
evaluating it:
if (denom != 0 && num / denom > 10)
Since the short-circuit form of AND (&&) is used, there is no risk of causing a run-time exception
when denom is zero. If this line of code were written using the single & version of AND, both sides
would be evaluated, causing a run-time exception when denom is zero. It is standard practice to
use the short-circuit forms of AND and OR in cases involving Boolean logic, leaving the single-
character versions exclusively for bitwise operations. However, there are exceptions to this rule.
For example, consider the following statement:
if(c==1 & e++ < 100) d = 100)
Here, using a single & ensures that the increment operation will be applied to e whether c is equal
to 1 or not.
Escape Sequences
Escape sequences in general are used to signal an alternative interpretation of a series of
characters.
For example, if you want to put quotes within quotes you must use the escape sequence, \",
on the interior quotes.
System.out.println("Good Morning \"World\" ");
Escape Sequence Description
\’ Single quote
\” Double quote
\\ Backslash
\r Carriage return
\n New Line
\t Tab
Program Structure, Compilation and Run Process
class Example
Here name of the class is Example.
public static void main(String args[])
public: The public keyword is an access specifier, which means that the content of
the following block accessible from all other classes.
static: The keyword static allows main() to be called without having to instantiate
a particular instance of a class.
void: The keyword void tells the compiler that main() does not return a value. The
methods can return value.
main(): main is a method called when a java application begins,
String args []
Declares a parameter named args, which is an array of instance of the class string.
Args[] receives any command-line argument present when the program is executed.
System.out.println()
System is predefined class that provides access to the system.
Out is the output stream that is connected to the console.
Output is accomplished by the built-in println() method. Println() displays the string
which is passed to it.
Example Example
javac java
.java .class
Type Casting
Assigning a value of one type to a variable of another type is known as Type Casting.
In Java, type casting is classified into two types,
Widening/Automatic Type Casting (Implicit)
If Statement
if statement is the most simple decision-making statement also known as simple if.
if statement consists of a Boolean expression followed by one or more statements.
If the expression is true, then 'statement-inside' will be executed, otherwise
'statement-inside' is skipped and only 'statement-outside' will be executed.
It is used to decide whether a block of statements will be executed or not i.e. if a
certain condition is true then a block of statement is executed otherwise not.
WAP to print if a number is positive
1. import java.util.*;
2. class MyProgram{
3. public static void main (String[] args){
4. int x;
5. Scanner sc = new Scanner(System.in);
6. x = sc.nextInt();
7. if(x > 0){
8. System.out.println("number is a positive");
9. }
10. }
if(condition 1)
{
statement-block1;
}
else if(condition 2)
{
statement-block2;
}
else if(condition 3)
{
statement-block3;
}
else if(condition 4)
{
statement-block4;
}
else
default-statement;
WAP to print if a number is zero or positive or negative
1. import java.util.*;
2. class MyProgram{
3. public static void main (String[] args){
4. int x;
5. Scanner sc = new Scanner(System.in);
6. x = sc.nextInt();
7. if(x > 0){
8. System.out.println(" number is a positive");
9. }
10. else if(x < 0) {
11. System.out.println(" number is a negative");
12. }
13. else{
14. System.out.println(" number is a zero");
15. }
16. }
Nested If statement
A nested if is an if statement that is the target of another if statement.
Nested if statements mean an if statement inside another if statement.
The statement connected to the nested if statement is only executed when -:
o Condition of outer if statement is true, and
o Condition of the nested if statement is also true.
Note: There could be an optional else statement associated with the outer if statement,
which is only executed when the condition of the outer if statement is evaluated to be
false and in this case, the condition of nested if condition won't be checked at all
if(condition 1)
{
if(condition 2)
{
nested-block;
}
else
{
nested-block;
}
}//if
else if(condition 3)
{
statement-block3;
}
else(condition 4)
{
statement-block4;
}
Nested If Program
1. int username = Integer.parseInt(args[0]);
2. int password = Integer.parseInt(args[1]);
3. double balance = 123456.25;
4. if(username==1234){
5. if(password==987654){
6. System.out.println("Your Balance is ="+balance);
7. }//inner if
8. else{
9. System.out.println("Password is invalid");
10. }
}//outer if
11. else{
12. System.out.println("Username is invalid");
13. }
14.
Switch case
n-way Decision
switch…case is a multi-way decision making statement.
It is similar to if-else-if ladder statement.
It executes one statement from multiple conditions.
switch (expression)
{
case constant 1:
// Statement-1
break;
case constant 2:
// Statement-2
break;
case constant 3:
// Statement-3
break;
default:
// Statement-default
// if none of the above case matches then this block would be
executed.
}
Introduction to loop
Repeatedly execute a block of statements
Looping Statements
Sometimes we need to repeat certain actions several times or till the some criteria is satisfied.
Loop constructs are used to iterate a block of statements several times.
Loop constructs repeatedly execute a block of statements for a fixed number of times or till
some condition is satisfied
Following are looping statements in any programming language,
o Entry Controlled while, for
o Exit Controlled do…while
o Unconditional Jump goto (It is advised to never use goto in a program)
Entry Controlled Loop: While
While is an entry controlled loop.
It executes a block of statements till the condition is true.
while(condition)
{
// true-block
}
int i = 1;
while (i <= 5)
{ System.out.println(i);
i++;
}
Nested loop
loop within a loop
Pattern Programs
WAP to print given pattern (nested loop)
1. public static void main(String[] args) {
2. int n=5;
3. for(int i=1;i<=n;i++){
4. for(int j=1;j<=i;j++){
5. System.out.print("*");
6. }//for j
7. System.out.println();
8. }//outer for i
9. }
10. }
WAP to print given pattern (nested loop)
1. class PatternDemo{
2. public static void main(String[] args) {
3. int n=5;
4. for(int i=1;i<=n;i++){
5. for(int j=1;j<=i;j++){
System.out.print(j+"\t");
6. }//for j
7. System.out.println();
8. }//outer for i
9. }
10. }
Mathematical functions
The Java Math class provides more advanced mathematical calculations other than
arithmetic operator.
The java.lang.Math class contains methods which performs basic numeric operations such
as the elementary exponential, logarithm, square root, and trigonometric functions.
All the methods of class Math are static.
Fields :
o Math class comes with two important static fields
E : returns double value of Euler's number (i.e 2.718281828459045).
PI : returns double value of PI (i.e. 3.141592653589793).
Math class Method:
Method Description
Math.abs() It will return the Absolute value of the given value.
Math.max() It returns the Largest of two values.
Math.min() It is used to return the Smallest of two values.
Math.round() It is used to round of the decimal numbers to the nearest value.
Math.sqrt() It is used to return the square root of a number.
Math.cbrt() It is used to return the cube root of a number.
Math.pow() It returns the value of first argument raised to the power to second
argument.
Math.signum() It is used to find the sign of a given value.
Math.ceil() It is used to find the smallest integer value that is greater than or equal to
the argument or mathematical integer.
Math.copySign() It is used to find the Absolute value of first argument along with sign
specified in second argument.
Math.nextAfter() It is used to return the floating-point number adjacent to the first
argument in the direction of the second argument.
Math.nextUp() It returns the floating-point value adjacent to d in the direction of positive
infinity.
Math.nextDown() It returns the floating-point value adjacent to d in the direction of
negative infinity.
Math.floor() It is used to find the largest integer value which is less than or equal to the
argument and is equal to the mathematical integer of a double value.
Math.floorDiv() It is used to find the largest integer value that is less than or equal to the
algebraic quotient.
Math.random() It returns a double value with a positive sign, greater than or equal
to 0.0 and less than 1.0.
Math.rint() It returns the double value that is closest to the given argument and equal
to mathematical integer.
Math.hypot() It returns sqrt(x2 +y2) without intermediate overflow or underflow.
Math.ulp() It returns the size of an ulp of the argument.
Math.getExponent() It is used to return the unbiased exponent used in the representation of
a value.
Math.IEEEremainder() It is used to calculate the remainder operation on two arguments as
prescribed by the IEEE 754 standard and returns value.
Math.addExact() It is used to return the sum of its arguments, throwing an exception if the
result overflows an int or long.
Math.subtractExact() It returns the difference of the arguments, throwing an exception if the
result overflows an int.
Math.multiplyExact() It is used to return the product of the arguments, throwing an exception if
the result overflows an int or long.
Math.incrementExact() It returns the argument incremented by one, throwing an exception if the
result overflows an int.
Math.decrementExact() It is used to return the argument decremented by one, throwing an
exception if the result overflows an int or long.
Math.negateExact() It is used to return the negation of the argument, throwing an exception if
the result overflows an int or long.
Math.toIntExact() It returns the value of the long argument, throwing an exception if the
value overflows an int.
Definition: An array is a fixed size sequential collection of elements of same data type grouped
under single variable name.
An array is a group of like-typed variables that are referred by a common name.
Arrays of any type can be created and may have one or more dimensions.
A specific element in an array is accessed by its index.
Arrays offer a convenient means of grouping related information.
int percentage[10];
Array declaration
Array declaration:
type var-name[];
Example:
Int student_marks[];
Above example will represent array with no value (null) To link student_marks
with actual, physical array of integers, we must allocate one using new keyword.
Example:
int student_marks[] = new int[20];
Normal Variable Declaration: int a;
Array Variable Declaration: int b[10];
Individual value or data stored in an array is known as an element of an
array.
Positioning / indexing of an elements in an array always starts with 0 not 1.
o If 10 elements in an array then index is 0 to 9
o If 100 elements in an array then index is 0 to 99
o If 35 elements in an array then index is 0 to 34
Variable a stores 1 integer number where as variable b stores 10 integer
numbers which can be accessed as b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7],
b[8] and b[9].
Important point about Java array
o An array is derived datatype.
o An array is dynamically allocated.
o The individual elements of an array is refereed by their
index/subscript value.
o The subscript for an array always begins with 0.
One-Dimensional Array
An array using one subscript to represent the list of elements is called one
dimensional array.
A One-dimensional array is essentially a list of like-typed variables.
Array declaration: type var-name[];
Example: int student_marks[];
Above example will represent array with no value (null).
To link student_marks with actual array of integers, we must allocate one
using new keyword.
Example:
int student_marks[] = new int[20];
WAP to count positive number, negative number and zero from an array of n size
1. import java.util.*;
2. class ArrayDemo1{
3. public static void main (String[] args){
4. int n,pos=0,neg=0,z=0;
5. int[] a=new int[5];
6. Scanner sc = new Scanner(System.in);
7. System.out.print("enter Array Length:");
8. n = sc.nextInt();
9. for(int i=0; i<n; i++) {
10. System.out.print("enter a["+i+"]:");
11. a[i] = sc.nextInt();
12. if(a[i]>0)
13. pos++;
14. else if(a[i]<0)
15. neg++;
16. else
17. z++;
18. }
19. System.out.println("Positive no="+pos);
20. System.out.println("Negative no="+neg);
21. System.out.println("Zero no="+z);
22. }}
Multidimensional Array
LinearSearchDemo.java
1. import java.util.*;
2. class LinearSearchDemo{
3. public static void main(String[] args) {
4. int size;
5. int a[]={1,2,3,4,5,6,7,8,9};
6. int search;
7. boolean flag=false;
8. Scanner sc=new Scanner(System.in);
9. System.out.print("Enter element to search");
10. search=sc.nextInt();
11. for(int i=0;i<a.length;i++){
12. if(a[i]==search){
13. System.out.println("element found at
"+i+"th index");
14. flag=true;
15. break;
16. } //if
17. }
18. if(!flag)
19. System.out.println("element NOT found!");
20. }
21. }
Output:
Enter element to search 6
element found at 5th index
Enter element to search 35
element NOT found!
Binary Search
The binary search first compares the key with the element in the middle of the
array. Consider the following three cases:
If the key is less than the middle element, you need to continue to search for
the key only in the first half of the array.
If the key is equal to the middle element, the search ends with a match.
If the key is greater than the middle element, you need to continue to search
for the key only in the second half of the array.
Binary Search Demo
1. import java.util.*;
2. class BinaryDemo{
3. public static void main(String[] args){
4. int size;
5. int a[]={1,2,3,4,5,6,7,8,9};
6. int search;
7. boolean flag=false;
8. Scanner sc=new Scanner(System.in);
9. System.out.print("Enter element to search:");
10. search=sc.nextInt();
11. int low=0;
12. int high= a.length-1;
13. while(high>=low){
14. int mid=(high+low)/2;
15. if(search==a[mid]){
16. flag=true;
17. System.out.println("element found
at "+mid+" index ");
18. break;
19. }
20. else if(search<a[mid]){
21. high=mid-1;
22. }
23. else if(search>a[mid]){
24. low=mid+1;
25. }
26. }//while
27. if(!flag)
28. System.out.println("element not found");
29. }
30. }
Output:
Enter element to search:5
element found at 4 index
Enter element to search:9
element found at 8 index
Enter element to search:56
element not found
Note: Array should be sorted in ascending order if we want to use Binary Search.
Sorting Array
Sorting, like searching, is a common task in computer programming. Many different
algorithms have been developed for sorting.
There are many sorting techniques available, we are going to explore selection sort.
Selection sort
o Finds the smallest number in the list and swaps it with the first element.
o It then finds the smallest number remaining and swaps it with the second element,
and so on, until only a single number remains.
Method with arguments and without return value: void add(int, int);
Method with arguments and with return value: int add(int, int);
Advantages of Method
Reduced Code Redundancy
Rewriting the same logic or code again and again in a program can be avoided.
Reusability of Code
Same function can be call from multiple times without rewriting code.
Reduction in size of program
Instead of writing many lines, just function need to be called.
Saves Development Time
Instead of changing code multiple times, code in a function need to be changed.
More Traceability of Code
Large program can be easily understood or traced when it is divide into functions.
Easy to Test & Debug
Testing and debugging of code for errors can be done easily in individual function.
Method Overloading
Definition: When two or more methods are implemented that share same name but
different parameter(s), the methods are said to be overloaded, and the
process is referred to as method overloading.
Method overloading is one of the ways that Java implements polymorphism.
When an overloaded method is invoked, Java uses the type and/or number of arguments
as its guide to determine which version of the overloaded method to actually call.
E.g. public void draw()
public void draw(int height, int width)
public void draw(int radius)
Thus, overloaded methods must differ in the type and/or number of their parameters.
While in overloaded methods with different return types and same name & parameter are
not allowed, as the return type alone is insufficient for the compiler to distinguish two
versions of a method.
Output:
add i=20
add i+j=80
add i+j+k=100
Method Overloading :Points to remember
Method overloading supports polymorphism because it is one way that Java
implements the “one interface, multiple methods” paradigm.
Overloading increases the readability of the program.
There are two ways to overload the method in java
o By changing number of arguments
o By changing the data type
In java, method overloading is not possible by changing the return type of
the method only because of ambiguity.
Scope Scope is defined as the area in which the declared variable is ‘accessible’.
There are five scopes: program, file, function, block, and class.
Scope is the region or section of code where a variable can be accessed.
Scoping has to do with when a variable is accessible and used.
Lifetime The lifetime of a variable is the period of time in which the variable is
allocated a space (i.e., the period of time for which it “lives”). There are
three lifetimes in C: static, automatic and dynamic.
Lifetime is the time duration where an object/variable is in a valid state.
Lifetime has to do with when a variable is created and destroyed
Visibility Visibility is the “accessibility” of the variable declared. It is the result of
hiding a variable in outer scopes.
Scope of a Variable
Scope Description
Local (block/function) "visible" within function or statement block from point of declaration
until the end of the block.
Class "seen" by class members.
File(program) visible within current file.
Global visible everywhere unless "hidden".
Lifetime of a variable
The lifetime of a variable or object is the time period in which the variable/object has
valid memory.
Lifetime is also called "allocation method" or "storage duration“.
Lifetime Stored
Static Entire duration of the program's execution. data segment
Automatic Begins when program execution enters the function or function call stack
statement block and ends when execution leaves the
block.
Dynamic Begins when memory is allocated for the object (e.g., heap
by a call to malloc() or using new) and ends when
memory is deallocated (e.g., by a call to free() or
using delete).
Local Variable Throughout the block/function in Until control leaves the block
which it is declared
Introduction to Classes in java
What is Class?
Class is derived datatype, it combines members of different datatypes into one.
Defines new datatype (primitive ones are not enough).
For Example: Car, College, Bus etc.
This new datatype can be used to create objects.
A class is a template for an object.
class Car{
String company;
String model;
double price;
double mileage;
………
}
Object Definition:
An Object is an instance of a Class.
An Object is a variable of a specific Class
An Object is a data structure that encapsulates data and functions in a single construct.
Object is a basic run-time entity
Objects are analogous to the real-world entities.
Creating Object & Accessing members
new keyword creates new object
Syntax:
ClassName objName = new ClassName();
Example :
SmartPhone iPhone = new SmartPhone();
Object variables and methods can be accessed using the dot (.) operator
Example: iPhone.storage = 8000;
Declaring an Object
When we create a class, we are creating a new data type.
Object of that data type will have all the attributes and abilities that are designed in
the class.
The new operator dynamically allocates (that is, allocates at run time) memory for an
object and returns a reference to it.
This reference is, more or less, the address in memory of the object allocated by new.
This reference is then stored in the variable. Thus, in Java, all class objects must be
dynamically allocated.
Here, r1 and r2 will both refer to the same Here, r1 has been set to null, but r2 still points
object. The assignment of r1 to r2 did not to the original object.
allocate any memory or copy any part of the
original object. It simply makes r2 refer to the
same object as does r1
WAP using class Person to display name and age
1. class MyProgram {
2. public static void main(String[] args) {
3. Person p1= new Person();
4. Person p2= new Person();
5. p1.name="modi";
6. p1.age=71;
7. p2.name="bachchan";
8. p2.age=80;
9. System.out.println("p1.name="+p1.name);
10. System.out.println("p2.name="+p2.name);
11. System.out.println("p1.age="+p1.age);
12. System.out.println("p2.age="+p2.age);
13. }//main()
14. }//class myProgram
Output:
enter height:30.55
enter width:20.44
Area=624.442
WAP using class Rectangle and calculate area with Return value
1. import java.util.*;
2. class MyProgram {
3. public static void main(String[] args){
4. float area;
5. Rectangle r1=new Rectangle();
6. Scanner sc=new Scanner(System.in);
7. System.out.print("enter height:");
8. r1.height=sc.nextFloat();
9. System.out.print("enter width:");
10. r1.width=sc.nextFloat();
11. area=r1.calArea();
12. System.out.println(“Area="+area);
13. }//main()
14. }//class myProgram
}
} //class
Properties of Constructor
Constructor is invoked automatically whenever an object of class is created.
Constructors do not have return types and they cannot return values, not even void.
All classes have constructors by default: if you do not create a class constructor yourself, Java
creates one for you known as default constructor.
Constructor is a method that is called at runtime during the object creation by using the new
operator. The JVM calls it automatically when we create an object.
It is called and executed only once per object.
It means that when an object of a class is created, constructor is called. When we create 2nd
object then the constructor is again called during the second time.
Types of Constructor
Default Constructor
A constructor defines what occurs when an object of a class is created.
Most classes explicitly define their own constructors within their class definition but if no
explicit constructor is specified then java will automatically supply a default constructor.
Once you define your own constructor, the default constructor is no longer used.
The default constructor automatically initializes all instance variables to zero.
It creates a new object by initializing the object with the instance of the same class.
types.
Destructor
Destructor is the opposite of the constructor. Constructor is used to initialize objects while
the destructor is used to delete or destroy the object that releases the resource occupied by
the object.
Definition: Destructor is an instance member function which is invoked automatically
whenever an object is going to be destroyed.
In other words, a destructor is the last function that is going to be called before an object is
destroyed.
In java, there is a special method named garbage collector that automatically called when an
object is no longer used.
When an object completes its life-cycle the garbage collector deletes that object and de-
allocates or releases the memory occupied by the object.
In C++, dynamically allocated objects must be manually released by use of a delete operator.
Java takes a different approach: it handles de-allocation automatically.
The technique that accomplishes this is known as “garbage collection”.
Why Destructor?
When we create an object of the class(using new), it occupies some space in the memory. If
we do not delete these objects, it remains in the memory and occupies unnecessary space.
To resolve this problem, we use the destructor.
Remember that there is no concept of destructor in Java.
Instead of destructor, Java provides the garbage collector that works the same as the
destructor.
The garbage collector is a program (thread) that runs on the JVM. It automatically deletes
the unused objects (objects that are no longer used) and free-up the memory.
The programmer has no need to manage memory, manually.
Static in Java
Characteristic of static method
A static method can call only other static methods and cannot call a non-static method from
it.
A static method can be accessed directly by the class name and doesn’t need any object
A static method cannot refer to “this” or “super” keywords in anyway
Static Block
Static block is executed exactly once, when the class is first loaded.
It is used to initialize static variables of the class.
It will be executed even before the main() method.
10. static {
11. System.out.println("Static block initialized.");
12. b= a * 5;
13. } //static block
14. public static void main(String args[]) {
15. System.out.println("inside main()...");
16. dispValue(44);
17. } //main()
18. } //class
Output:
Static block initialized.
inside main()...
Static method initialized.
x = 44
a = 4
b = 20
Nested Class
Nested Class: Class within another class
Scope: Nested class is bounded by the scope of its enclosing class.
o E.g. class B is defined within class A, then B is known to A, but not outside of A.
A nested class has access to the members, including private members of the class in which it
is nested.
However, the enclosing class does not have access to the members of the nested class. i.e.
Class B can access private member of class A, while reverse is not accessible.
Types of Nested class:
We can import all the classes/interfaces of other package using a import keyword at the first
line of code with the wildcard (*).
import java.util.*;
public class DemoImport {
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
Date d = new Date();
// Code
}
}
It is possible to use classes from other packages without importing the class using fully
qualified name of the class.
Example :
java.util.Scanner s = new java.util.Scanner(System.in);
Static Import
The static import feature of Java 5 facilitate the java programmer to access any static
member of a class directly.
Advantage: Less coding is required if you have to access any static member of a class more
frequently.
Disadvantage: If you overuse the static import feature, it makes the program unreadable
and unmaintainable.
import static java.lang.System.out;
public class S2{
public static void main(String args[]){
out.println("Hello main");
}
}
Access Control
What is OOP?
OOP (Object-Oriented Programming) is a programming paradigm that is completely based
on ‘objects’.
Object-Oriented Programs insists to have a lengthy and extensive design phase, which results
in improved designs and fewer defects.
Object-oriented programming provides a higher level way for programmers to envision and
develop their applications.
In an object-oriented programming language, less emphasis is placed upon the flow of
execution control. Instead, the program is viewed as a set of objects interacting with each
other in defined ways.
An OOP programmer can bind new software objects to make completely new
programs/system.
What is Object-Orientation?
Object-oriented modeling and design is a way of thinking about problems using models
organized around real-world concepts.
The fundamental construct is object, which combine data structure and behavior.
Object-Oriented Models are useful for
o Understanding problems
o Communicating with application experts
o Modeling enterprises
o Preparing documentation
o Designing System
Inheritance
The mechanism of a class to derive properties and characteristics from another class is
called Inheritance.
Inheritance is the process, by which a class can acquire(reuse) the properties and methods
of another class.
The mechanism of deriving a new class from an old class is called inheritance.
The new class is called derived class and old class is called base class.
It is the most important feature of Object Oriented Programming.
Base Class: The class whose properties are inherited by sub class is called Base Class/Super
class/Parent class.
Derived Class: The class that inherits properties from another class is called Sub
class/Derived Class/Child class.
Inheritance is implemented using super class and sub class relationship in object-oriented
languages.
The derived class may have all the features of the base class and the programmer can add
new features to the derived class.
Inheritance is also known as “IS-A relationship” between parent and child classes.
For Example :
o Car IS A Vehicle
o Bike IS A Vehicle
o EngineeringCollege IS A College
o MedicalCollege IS A College
o MCACollege IS A College
Inheritance: Advantages
Promotes reusability
When an existing code is reused, it leads to less development and maintenance costs.
It is used to generate more dominant objects.
Avoids duplicity and data redundancy.
Inheritance makes the sub classes follow a standard interface.
Implementing Inheritance
To inherit a class, you simply incorporate the definition of one class into another by using
“extends” keyword.
Syntax:
class subclass-name extends superclass-name {
// body of class…
}
Property of Inheritance
InheritanceDemo.java
1. class A{
2. protected int i;
3. int j;
4. void showij(){
5. System.out.println("i="+i+" j="+j);
6. }
7. }
Single Inheritance
Output:
inside default Constructor:CUBE
inside Constructor:CUBEWEIGTH
inside default Constructor:CUBE
inside Constructor:CUBEWEIGTH
cw1.volume()=1000.0
cw2.volume()=1000000.0
Super Keyword
Whenever a subclass needs to refer to its immediate superclass, it can do so by use of the
keyword super.
Super has two general forms:
1. Calls the superclass constructor.
2. Used to access a members (i.e. instance variable or method) of the superclass.
This second form of super is most applicable to situations in which member names of a
subclass hide members by the same name in the superclass.
Using super to access members
1. class A{
2. int i;
3. }
4. class B extends A{
5. int i,k;
6. B(int a,int b){
7. super.i=a;
8. this.i=b;
9. }
10. void show(){
11. System.out.println("super.i="+super.i);
12. System.out.println("this.i="+this.i);
13. }
14. }
15. class SuperMemberDemo{
16. public static void main(String[] args)
17. {
18. B b= new B(12,56);
19. b.show();
20. }
21. }
Output:
super.i=12
this.i=56
Access Control
Access Modifier Description
Private(-) The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
Default(~) The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will
be the default.
Protected(#) The access level of a protected modifier is within the package and outside the
package through child class. If you do not make the child class, it cannot be
accessed from outside the package.
Public(+) The access level of a public modifier is everywhere. It can be accessed from within
the class, outside the class, within the package and outside the package.
Polymorphism
Polymorphism: It is a Greek term means, “One name many Forms”.
Polymorphism: Advantages
Single variable can be used to store multiple data types.
Easy to debug the codes.
It allows to perform a single act in different ways.
Polymorphism allows the object to decide which form of the function to implement at
compile-time (overloading) as well as run-time (overriding).
Reduces coupling, increases reusability and makes code easier to read.
Implementing Polymorphism
Method Overriding
In a class hierarchy, when a method in a subclass has the same name and type signature as a
method in its superclass, then the method in the subclass is said to override the method in the
superclass.
Definition: If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in Java.
Method Overriding Demo
1. class Shape{
2. void draw(){
3. System.out.println("Draw Shape");
4. }
5. }
6. class Circle extends Shape{
7. void draw(){
8. System.out.println("Draw Circle");
9. }
10. }
11. class Square extends Shape{
12. void draw(){
13. System.out.println("Draw Square");
14. }
15. }
16. class OverrideDemo{
17. public static void main(String[] args) {
18. Circle c= new Circle();
19. c.draw(); //child class meth()
20. Square sq= new Square();
21. sq.draw();//child class meth()
22. Shape sh= new Shape();
23. sh.draw();//parentClass meth()
24. }
25. }
Output:
Draw Circle
Draw Square
Draw Shape
Why Overriding?
Method overriding is used to provide the specific implementation of a method which is already
provided by its superclass.
Method overriding is used for runtime polymorphism.
By combining inheritance with overridden methods, a superclass can define the general form
of the methods that will be used by all of its subclasses.
Dynamic, run-time polymorphism is one of the most powerful mechanisms that object-
oriented design brings to bear on code reuse and robustness.
“final” keyword
The final keyword is used for restriction.
final keyword can be used in many context
Final can be:
1. Variable
If you make any variable as final, you cannot change the value of final variable (It will be
constant).
2. Method
If you make any method as final, you cannot override it.
3. Class
If you make any class as final, you cannot extend it.
“final” as a variable
Cannot change the value of final variable.
“final” as a method
If you make any method as final, you cannot override it.
class BikeClass{
final void run(){
System.out.println("Running Bike");
}
}
Encapsulation
The action of enclosing something in.
In OOP, encapsulation refers to the bundling of data with the methods.
E.g. Interface and Abstract Class E.g. Access Modifier (public, protected,
private)
Purpose: Reduce code complexity Purpose: Data protection
Implementing Abstraction
Abstraction is a process of hiding the implementation details from the user, only the
functionality will be provided to the user.
In other words, the user will have the information on what the object does instead of how the
object will do it.
Abstraction is achieved using Abstract classes and interfaces.
A class which contains the abstract keyword in its declaration is known as abstract class.
o Abstract classes may or may not contain abstract methods, i.e., methods without
body ( public void get(); )
o But, if a class has at least one abstract method, then the class must be declared
abstract.
o If a class is declared abstract, it cannot be instantiated.
o To use an abstract class, we have to inherit it to another class and provide
implementations of the abstract methods in it.
Abstract class
Abstract class (Example)
1. abstract class Car {
2. public abstract double getAverage();
3. }
4. class Swift extends Car{
5. public double getAverage(){
6. return 22.5;
7. }
8. }
9. class Baleno extends Car{
10. public double getAverage(){
11. return 23.2;
12. }
13. }
14. public class MyAbstractDemo{
15. public static void main(String ar[]){
16. Swift s = new Swift();
17. Baleno b = new Baleno();
18. System.out.println(s.getAverage());
19. System.out.println(b.getAverage());
20. }
21. }
Interface: Syntax
39. System.out.println("MyStack2=");
instanceof operator
Syntax:
(Object reference variable ) instanceof (class/interface type)
Example:
boolean result = name instanceof String;
Wrapper classes
A Wrapper class is a class whose object wraps or contains a primitive datatypes.
When we create an object to a wrapper class, it contains a field and in this field, we can store
a primitive datatypes.
In other words, we can wrap a primitive value into a wrapper class object.
Use of wrapper class :
o They convert primitive datatypes into objects.
o The classes in java.util package handles only objects and hence wrapper classes help
in this case also.
o Data structures in the Collection framework, such as ArrayList and Vector, store only
objects (reference types) and not primitive types.
o An object is needed to support synchronization in multithreading.
Primitive datatypes: Wrapper class
Primitive datatype Wrapper class Example
byte Byte Byte b = new Byte((byte) 10);
short Short Short s = new Short((short) 10);
int Integer Integer i = new Integer(10);
long Long Long l = new Long(10);
float Float Float f = new Float(10.0);
double Double Double d = new Double(10.2);
char Character Character c = new Character('a');
boolean Boolean Boolean b = new Boolean(true);
The BigDecimal class found in java.math package provides operation for arithmetic,
comparison, hashing, rounding, manipulation and format conversion.
o This method can handle very small and very big floating point numbers with great
precision.
An object of the String class represents a string of characters.
The String class belongs to the java.lang package, which does not require an import
statement.
Like other classes, String has constructors and methods.
String class has two operators, + and += (used for concatenation).
Empty String :
An empty String has no characters. Its length is 0.
String Class
In java, a string is a sequence of characters. But, unlike many other languages that
implement strings as character arrays, java implements strings as objects of type String.
When we create a String object, we are creating a string that cannot be changed. That is,
once a String object has been created, we cannot change the characters that comprise that
string. We can perform all types of operations.
For those cases in which a modifiable string is desired, java provides two options:
StringBuffer and StringBuilder. Both hold strings that can be modified after they are
created.
The String, StringBuffer and StringBuilder classes are defined in java.lang. Thus, they are
available to all programs automatically. All three implements CharSequence interface.
String Constructor
The String class support several constructors. To create an empty String, you call the default
constructor.
For example,
String s=new String();
this will create an instance of with no characters in it.
String s = new String(“Computer Deparatment”);
class StringEx
{
public static void main(String args[])
{
String s1=new String("Computer Department");
String s2;
s2=s1 + "Darshan University";
System.out.println(s2);
}
}
String Immutability
Advantage Disadvantage
Convenient — Immutable objects are Less efficient — you need to create a new string
convenient because several references can and throw away the old one even for small
point to the same object safely. changes.
String name="DIET - Rajkot"; String word = "java";
foo(name); char ch = Character.toUpperCase(
//Some operations on String name word.charAt (0));
name.substring(7,13); word = ch + word.substring (1);
bar(name);
String Methods
Method Call Task Performed
S2=s1.toLowerCase; Conver ts the string s1 to lowercase
S2=s1.toUpperCase; Converts the string s1 to uppercase
S2=s1.replace(‘x’,’y’) Replace all appearances of x with y.
S2=s1.trim() Remove white spaces at the beginning and end of the string s1
S1.equals(s2) Returns true if s1 and s2 are equal
S1.equalsIgnoreCase(s2) Returns true if s1=s2, ignoring the case of characters
S1.length() Gives the length of s1
S1.CharAt(n) Gives the nth character of s1
S1.compareTo(s2) Returns –ve if s1<s2, +ve if s1>s2, and 0 if s1=s2
S1.concat(s2) Concatenates s1 and s2
S1.substring(n) Gives substring starting from nth character.
S1.substring(n,m) Gives substring starting from nth char up to mth
toString() This object (which is already a string!) is itself returned.
S1.indexOf(‘x’) Gives the position of the first occurrence of ‘x’ in the string s1
S1.indexOf(‘x’,n) Gives the position of ‘x’ that occurs after nth position in the string s1
String.ValueOf(variable) Converts the parameter value of string representation
StringBuffer
The java.lang.StringBuffer class is a thread-safe, mutable sequence of characters.
Following are the important points about StringBuffer:
A string buffer is like a String, but can be modified (mutable).
It contains some particular sequence of characters, but the length and content of
the sequence can be changed through certain method calls.
They are safe for use by multiple threads.
StringBuffer defines these Constructor:
StringBuffer()
StringBuffer(int size)
StringBuffer(String str)
StringBuffer(CharSequence chars)
Remember : “StringBuffer” is mutable
As StringBuffer class is mutable, we need not to replace the reference with a new reference
as we have to do it with String class.
StringBuffer str1 = new StringBuffer("Hello Everyone");
str1.reverse();
// as it is mutable can not write str1 = str1.reverse();
// it will change to value of the string itself
System.out.println(str1);
// Output will be “enoyrevE olleH”
StringBuffer Methods
Method Description
append(String s) Used to append the specified string with this string.
insert(int offset, String s) Used to insert the specified string with this string at the
specified position.
replace(int startIndex, int endIndex, Used to replace the string from specified startIndex and
String str) endIndex.
delete(int startIndex, int endIndex) Used to delete the string from specified startIndex and
endIndex.
reverse() Used to reverse the string.
String Builder
Java StringBuilder class is used to create mutable string.
The Java StringBuilder class is same as StringBuffer class except that it is non-synchronized.
It is available since JDK 1.5.
It has similar methods as StringBuffer like append, insert, reverse etc…
ArrayList
The java.util.ArrayList class provides resizable-array and implements the List interface.
Following are the important points about ArrayList:
It implements all optional list operations and it also permits all elements, including null.
It provides methods to manipulate the size of the array that is used internally to store the
list.
ArrayList (constructors) :
Sr Constructor & Description
1 ArrayList()
This constructor is used to create an empty list with an initial capacity sufficient to hold
10 elements.
2 ArrayList(Collection<? extends E> c)
This constructor is used to create a list containing the elements of the specified
collection.
3 ArrayList(int initialCapacity)
This constructor is used to create an empty list with an initial capacity.
ArrayList (method)
Sr Method & Description
1 void add(int index, E element)
This method inserts the specified element at the specified position in this list.
2 boolean addAll(Collection<? extends E> c)
This method appends all of the elements in the specified collection to the end of this list,
in the order that they are returned by the specified collection's Iterator
3 void clear()
This method removes all of the elements from this list.
4 boolean contains(Object o)
This method returns true if this list contains the specified element.
5 E get(int index)
This method returns the element at the specified position in this list.
6 int indexOf(Object o)
This method returns the index of the first occurrence of the specified element in this list,
or -1 if this list does not contain the element.
7 boolean isEmpty()
This method returns true if this list contains no elements.
8 int lastIndexOf(Object o)
This method returns the index of the last occurrence of the specified element in this list,
or -1 if this list does not contain the element.
9 boolean remove(Object o)
This method removes the first occurrence of the specified element from this list, if it is
present.
10 E set(int index, E element)
This method replaces the element at the specified position in this list with the specified
element.
11 int size()
This method returns the number of elements in this list.
12 Object[] toArray()
This method returns an array containing all of the elements in this list in proper sequence
(from first to last element).