Unit 01 Java Programming
Unit 01 Java Programming
Unit-1
Object-Oriented Thinking
A way of Viewing the World
• YouTube link:
https://www.youtube.com/watch?v=f7rT0h1Q5Wo
Hello world program
class Test
{
public static void main(String args[])
{
System.out.println("Hello World");
}
}
Execution of a Java Program
The Java Buzzwords
• Java Is Object-Oriented
• Java Is Simple
• Java Is Secure
• Java Is Platform Independent
• Java Is Robust
• Java Is Portable
• Java Is Architecture-Neutral
• Java Is Dynamic
• Java Is Interpreted and High
performance
• Java Is Multithreaded
• Java Is Distributed
Java Buzzwords (cont.)
• Object-oriented: Java is designed around the
concept of objects, which encapsulate data and
behavior. It supports principles such as Abstraction,
Encapsulation, Inheritance and Polymorphism.
• Simple: Java is designed to be easy to learn and use,
with syntax similar to C++. It avoids complex features
present in other languages like pointers and operator
overloading.
Java Buzzwords (cont.)
• Secure: Java's robust security features include
a bytecode verifier to ensure code integrity,
runtime security checks, and a security manager
to control access to system resources.
• Robust: Java emphasizes reliability through
features like strong memory management,
exception handling, and type checking.
Java Buzzwords (cont.)
• Portable: Java's "Write Once, Run Anywhere" (WORA)
philosophy enables developers to write code once and
deploy it across multiple platforms without modification.
• Platform-independent: Java programs can run on any
device or platform that supports Java Virtual Machine
(JVM), making it highly portable.
• Architecture-neutral: Java is architecture neutral
because there are no implementation dependent
features, for example, the size of primitive types is fixed.
Java Buzzwords (cont.)
• Interpreted: Java source code is initially compiled into
bytecode, which is a platform-independent intermediate
representation. This bytecode is then interpreted by the
Java Virtual Machine (JVM) at runtime. This interpretation
allows Java programs to be executed on any system with a
compatible JVM without the need for recompilation.
• High performance: While Java's performance was initially
a concern, advancements in JVM technology and just-in-
time (JIT) compilation have significantly improved its
execution speed.
Java Buzzwords (cont.)
• Dynamic: Java supports dynamic loading of classes,
which enables applications to dynamically extend their
functionality.
• Distributed: Java is designed to make distributed
computing easy with Technologies like RMI(Remote
Method Invocation) and EJB(Enterprise Java Bean).
• Multithreaded: Java provides built-in support for
multithreading, allowing concurrent execution of
multiple threads within a single program.
Java Scanner class
• Prior to Java 1.5 getting input from the console involved multiple
steps.
• Java 1.5 introduced the Scanner class which simplifies console input.
• It is used to read from files and Strings (among other sources).
• Scanner is in the java.util package. So you must:
import java.util.Scanner;
• Scanner class is used for obtaining the input of the primitive types like
int,double,strings, etc.
• To create an object of Scanner class, we usually pass the predefined
object System.in, which represents the Standard input stream.
Creating Scanner objects
• Constructing a Scanner object to read console
input:
Scanner name = new Scanner(System.in);
– Example:
Scanner s = new Scanner(System.in);
**At the same time you are calling the constructor of the
class, with the parameter System.in
Scanner class methods
Method Description
nextBoolean() Reads a boolean value from the user
nextByte() Reads a byte value from the user
nextDouble() Reads a double value from the user
nextFloat() Reads a float value from the user
nextInt() Reads a int value from the user
nextLine() Reads a String value from the user
nextLong() Reads a long value from the user
nextShort() Reads a short value from the user
Example
import java.util.Scanner;
class Example
{
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
System.out.println(“Enter your name:”);
String name = s.nextLine();
System.out.println(“Name = “+name);
}
}
How to create real world entity in
Java?
Class Account
{
State
-
-
Behavior
-
-
}
How to create object?
Account a;
• a is used to point an object but still not pointing
a = new Account();
• new is an operator
• a is a pointer reference to object(memory)
• Account is the object
– is for subtraction.
* is for multiplication.
/ is for division.
% is for modulo.
Note: Modulo operator returns remainder, for example
10 % 5 would return 0
Assignment operators
Assignments operators in java are: =, +=, -=, *=, /=, %=
a = b would assign value of variable b to the variable a.
++ and - -
a++ is equivalent to a=a+1;
a- - is equivalent to a=a-1;
Logical operators
• Logical Operators are used with binary variables.
• They are mainly used in conditional statements and loops for evaluating
a condition.
Logical operators in java are: &&, ||, !
Let’s say we have two boolean variables x and y.
x&&y will return true if both x and y are true else it would return false.
x||y will return false if both x and y are false else it would return true.
!x would return the opposite of x, that means it would be true if x is false
and it would return false if x is true.
Comparison (Relational) operators
We have six relational operators in Java: ==, !=, >, <, >=, <=
== returns true if both the left side and right side are equal
!= returns true if left side is not equal to the right side of operator.
>= returns true if left side is greater than or equal to right side.
<= returns true if left side is less than or equal to right side.
Bitwise operators
There are six bitwise Operators: &, |, ^, ~, <<, >>
x = 11; /* equal to 00001011*/
y = 22; /* equal to 00010110 */
Bitwise operator performs bit by bit processing.
x & y compares corresponding bits of x and y and generates 1 if both bits are
equal, else it returns 0. In our case it would return: 2 which is 00000010
because in the binary form of x and y only second last bits are matching.
x | y compares corresponding bits of x and y and generates 1 if either bit
is 1, else it returns 0. In our case it would return 31 which is 00011111
x ^ y compares corresponding bits of x and y and generates 1 if they are
not equal, else it returns 0. In our example it would return 29 which is
equivalent to 00011101
Bitwise operators
~x is a complement operator that just changes the bit from 0 to 1 and 1 to 0. In
our example it would return -12 which is signed 8 bit equivalent to 11110100
x << 2 is left shift operator that moves the bits to the left, discards the far left
bit, and assigns the rightmost bit a value of 0. In our case output is 44 which is
equivalent to 00101100
Note: In the example below we are providing 2 at the right side of this shift
operator that is the reason bits are moving two places to the left side. We can
change this number and bits would be moved by the number of bits specified
on the right side of the operator. Same applies to the right side operator.
x >> 2 is right shift operator that moves the bits to the right, discards the far
right bit, and assigns the leftmost bit a value of 0. In our case output is 2 which
is equivalent to 00000010
Ternary operator
This operator evaluates a boolean expression and assign the value based on the
result.
Syntax:
If the expression results true then the first value before the colon (:) is assigned to
the variable h else the second value is assigned to the h.
Operator precedence in Java
This determines which operator needs to be evaluated first if an expression has
more than one operator. Operator with higher precedence at the top and lower
precedence at the bottom.
Unary Operators ++ – – ! ~
Multiplicative * /%
Additive + –
Shift << >> >>>
Relational > >= < <=
Equality == !=
Bitwise AND &
Bitwise XOR ^
Bitwise OR |
Logical AND &&
Logical OR ||
Ternary ?:
Assignment = += -= *= /= %= > >= < <= &= ^= |=
instanceOf operator
• The java instanceof operator is used to test whether the
object is an instance of the specified type (class or subclass
or interface).
• The instanceof in java is also known as type comparison
operator because it compares the instance with type. It
returns either true or false. If we apply the instanceof operator
with any variable that has null value, it returns false.
• Example
class Simple1{
public static void main(String args[]){
Simple1 s=new Simple1();
System.out.println(s instanceof Simple1);//true
}
}
Arrays
• Array is a collection of group of similar data types
• Arrays are used to store multiple values in a single variable, instead
of declaring separate variables for each value.
• Array in java is index-based, the first element of the array is stored at
the 0 index.
4 Steps to use arrays in java
1. Declaring an Array
2. Creating an array/giving memory
3. Initializing the array
4. Using an array/ accessing the array
1. Declaring an Array
class Demo
1.dataType[] arr; {
2.dataType []arr; public static void main(String args[])
3.dataType arr[];
4.dataType[] arr1,arr2,arr3; {
int[] arr;
Example
int []arr;
int[] arr; int arr[];
int []arr;
int arr[]; int[] arr1,arr2,arr3;
int[] arr1,arr2,arr3; }
}
2. Creating an array and giving memory or instantiating array
class Demo
1.Array is an object {
2.It has to created using new operator
public static void main(String args[])
Example
{
int arr[]=new int[10]; int[] arr;
arr=new int[10];
import java.util.Scanner;
class Demo class Demo
{ {
public static void main(String args[]) public static void main(String args[])
{
Scanner obj=new Scanner(System.in);
{
int arr[]; int a[]={33,3,4,5};
arr=new int[10]; }
for(int i=1;i<arr.length;i++) }
{
arr[i]=obj.nextInt();
}
} Declaring ,instantiating and initializing in single li
}
3. Initializing the array
class Demo class Demo
{ {
public static void main(String args[]) public static void main(String args[])
{ {
int[] num3; int[] num3;
num3={3,4,5,6}; Not a valid statement num3=new int[]{3,4,5,6};
} }
} }
4. Accessing the elements
class Demo
{
public static void main(String args[])
{
int[] num3;
num3=new int[]{3,4,5,6};
for(int i=0;i<num3.length;i++)
{
System.out.println(num3[i]);
}
}
}
Java program to read n elements and display n
elements using array
For example :
marks = new int[3][4];
More on 2-D Array Creation
int marks[][] = new int[][]; / / incorrect;
int marks[][] = new int[][4] / / incorrect;
marks=new int[3][4];
Initialization of 2-D Array
• After array creation we can initialize the 2-D array like this :
• Arrayvariable[row][column]= value;
Row 0 8 9 10 7
Row 1 12 21 30 7
Row 2 31 45 10 40
Col 0 Col 1 Col 2 Col 3
8 9 10 7
Row 0
12 21 30 7
Row 1
31 45 10 40
Row 2
System.Out.Println(marks[1][2]);
output = 30
System.Out.Println(marks[0][0]);
output = 8
We can also initialize the array at the time
of array creation
int[][] marks = new int{
{1,2,0,5},
{4,5,1,4},
{7,6,5,9}
}
How we can get array length
import java.util.Scanner;
public class Ex2DArray
{ //To print matrix
public static void main(String args[]) System.out.print("The Array is :\n");
{ for(i=0; i<row; i++)
int row, col, i, j;
{
int arr[][] = new int[10][10];
Scanner scan = new Scanner(System.in); for(j=0; j<col; j++)
System.out.print("Enter row for the array (max 10) : "); {
row = scan.nextInt(); System.out.print(arr[i][j]+ " ");
System.out.print("Enter column for the array (max 10) : "); }
col = scan.nextInt(); System.out.println();
//To Read matrix elements
}
System.out.println("Enter " +(row*col)+ " Array Elements : ");
for(i=0; i<row; i++)
}
{ }
for(j=0; j<col; j++)
{
arr[i][j] = scan.nextInt();
}
}
Jagged Array (non-rectangular array)
Disadvantages
• Size Limit: We can store only the fixed size of elements in the
array. It doesn't grow its size at runtime.
Heap Stack
Local
variables
Objects
Primitive
data types 3
Strings
• Strings in Java are different, right from the start. You may have
noticed that all of the primitive types are written in all lower
case letters. String needs a capital S.
• A primitive data type can be changed again and again by
reassigning the value, a string can’t be changed once it set.
WAYS OF CREATING STRING IN JAVA
• Using String Literal.
• Using “new” keyword.
USING STRING LITERAL
• To check this, you can compare two String references using ==
operator to check whether two references are referring to the
same String object in the memory.
• Example:
String s1 = “Java";
String s2 = “Java";
if(s1 == s2)
System.out.println("s1 and s2 referring to the same
object.");
USING “new” KEYWORD
• In Java, strings are objects. As with other objects, we can
create an instance of a string with the new keyword, as
follows:
String s = new String(“Java”);
• This line of code creates a new object of class String and
assigns it to the reference variable s
• So far, String objects seem just like other objects. Now, let's
give the string a value:
s = “java";
Strings are immutable objects
String x = "Java";
x.concat(" Rules!");
System.out.println("x = " + x);
Output: x = Java
String is immutable object .
Immutable means once created cannot be changed
The object created as a String is stored in the Constant String
Pool.
Every immutable object in Java is thread safe, that implies String is
also thread safe .
String cannot be used by two threads simultaneously.
String once assigned cannot be changed.
String a=“Hello World”;
//The above object is stored in constant String pool and its value
cannot be modified
a+=“Java Programming”;
//“Hello World" string still exists in string constant pool and its
value is not overrided but we lost reference to the “Hello World“
String. 4
Example with CODE
Heap
Hello World
Heap
Hello 5
World
Example with CODE
:String
Life is a tale told by an
idiot
It can no longer be
accessed
:String
Shakespeare
Life is a tale told by an
idiot
6
Important Methods in String Class
char charAt(int index): Returns the character at the specified index
String concat(Sring str): Appends a string to the end of another
string
int length(): Returns the length of a specified string
String substring(int beginindex): returns substring for given begin
index
String substring(int begin, int end): returns substring for given begin
index and end index
String toLowerCase(): returns a string in lowercase
String toUpperCase(): returns a string in uppercase
String trim(): removes beginning and ending spaces of this string
boolean contains(CharSequence s): returns true or false after
matching the sequence of char value
static String join(CharSequence delimiter, CharSequence...
elements): returns a joined string
boolean equals(Object another): checks the equality of string with
the given object
static String equalsIgnoreCase(String another): compares another
string. It doesn't check case
boolean isEmpty(): checks if string is empty
String replace(char old, char new): replaces all occurrences of the
specified char value
String replace(CharSequence old, CharSequence new): replaces all
occurrences of the specified CharSequence
int indexOf(char ch): returns the specified char value index
String[] split(String regex): returns a split string matching regex
Disadvantage of String
String Builder
StringBuilder is same as the StringBuffer , that is it stores the
object in heap and it can also be modified .
The main difference between the StringBuffer and
StringBuilder is that StringBuilder is also not thread safe.
Yes Yes No
Thread
Safe
Modifi
able immutable mutable mutable
Process of Concatenation of String And
StringBuffer
String can be concatenated by using “+” operator or .concat() method.
StringBuffer can be concatenated by using append().
While concatenating StringBuffer is faster than String
StringTokenizer
• StringTokenizer class is used for creating tokens in Java. It
allows an application to break or split into small parts. Each
split string part is called Token.
StringTokenizer Constructors
StringTokenizer(String str): str is a string to be tokenized and it
considers default delimiters like newline, space, tab, carriage
return and form feed which can be further tokenized.
StringTokenizer(String str, String delim): delim is set of
delimiters that are used to tokenize the given string.
StringTokenizer(String str, String delim, boolean flag): Since
the first two parameters have the same meaning. If the flag is
false, delimiter characters serve to separate tokens and if the
flag is true, delimiter characters are considered to be tokens.
StringTokenizer Methods
• hasMoreTokens(): return True if and only if next token to the
current position in the string exists, else false.
• nextToken(): returns next token from the given
StringTokenizer.
• countTokens(): returns total number of tokens which are
present
• nextElement(): This method returns Object rather than String.
Works similar to nextToken exists so that this class can
implement the Enumeration interface.
• hasMoreElements(): returns True if tokens are present in the
string, else false.
Inheritance
Introduction
• In Java it is possible to inherit attributes and methods
from one class to another
• Inheritance
– Subclass (Child): The class that inherits from another
• Terms in Inheritance
– Class
– Subclass/Child class
– Reusability
Introduction
• Syntax
Class subclass_name extends superclass_name
/*The extends keyword indicates that you are making a new class that
derives from an existing class. The meaning of “extends” is to increase
the functionality*/
Introduction
• Types of Inheritance
– Single Class A
Class B
– Multilevel
Class A
Class B
Class C
Introduction
• Types of Inheritance
– Hierarchical
Class A
Class B Class C
– Multiple
Class A Class B
Class C
• Note:
– The base class constructor call must be the first line in
derived class constructor
super keyword
• The super keyword in Java is a reference variable
which is used to refer immediate parent class object.
• Whenever you create the instance of subclass, an
instance of parent class is created implicitly which is
referred by super reference variable.
• Usage of Java super Keyword
1. super can be used to refer immediate parent class
instance variable.
2. super can be used to invoke immediate parent class
method.
3. super() can be used to invoke immediate parent
class constructor.
Static Initialization Block &
Instance Initialization Block
Static Initialization Block Instance Initialization Block
No keyword is required to define an
To define a static initialization block
instance initialization block.
we use the keyword static
A static initialization block loads as
An instance initialization block is only
soon as a class loads and it is not
executed when there is a call to the
associated with a call to the
constructor for creating an object.
constructor of a class for object
creation.
An instance initialization block can
not only access static variables and
Static block can only access static
static methods but also instance
variables and static methods of its
variables and instance methods of
class
the class.
An instance initialization block
always makes an automatic call to
There is no automatic call to
superclass constructor by calling
superclass constructor from the
super() before executing any other
static initialization block.
statement in it.
Base
Test
void fun(int a)
void fun(int a)
void fun(int a,int b)
void fun(char a)
Derived
void fun(int a)
Ad-Hoc Polymorphism
• Method overloading is an example of Ad-hoc or compile time polymorphism.
class Overload
{
void demo()
{ In this example, demo() method is
}
void demo(int a) overloaded 3 times, which method
{
} is to be called is determined by the
void demo(int a,int b)
{ arguments we pass while calling
}
public static void main(String args[]) methods, this happens in compile
{
Overload p=new Overload(); time so it is known as compile
p.demo();
p.demo(10); time polymorphism
p.demo(10,20);
} }
Pure Polymorphism
• Method overriding is an example of pure or run time polymorphism.
class A
{
void demo()
{
} In this example, demo() method of
}
class B extends A parent class A is override by child
{
void demo() class B. We can access the method
{
} in either A or B at the time of
}
class Overridde object creation using parent class
{
public static void main(String args[]) reference and this is done at run
{
A a=new b(); time
a.demo();
}
}
Rules for overriding
• Both the superclass and the subclass must have the same method name, the same
return type and the same parameter list.
• Overriding and Access-Modifiers : The access modifier for an overriding method can
allow more, but not less, access than the overridden method. For example, a
protected instance method in the super-class can be made public, but not private, in
the subclass. Doing so, will generate compile-time error.
• 1) If programmer makes any mistake such as wrong method name, wrong parameter
types while overriding, you would get a compile time error.
Person class
Employee class
Example:
Example:
Base Derived
Example:
Base Derived
M1() Defined with new
M1() M2()
M2() code
M3()
New method
Forms of Inheritance
5. Limitation:
Example:
6. Combination:
2) Extensibility
Extending the base class logic as per business logic of the derived class
3) Data binding
Base class can decide to keep some data private so that it cannot be altered by
the derived class
4) Overriding
Override methods of the base class so that meaningful implementation can be
designed in the derived class based on business logic
Disadvantages
1) Increased time/effort to jump through all the levels of overloaded classes
Example:
If a given class has 10 levels of abstraction then it has to take 10 jumps
to run through a function defined in each of their classes
2) During maintenance adding new features will effect both base class and
derived class. They both required to be changed. Example: change in
method signature
3) In case of deleting a particular method in base class, things get a bit
complicated in case of inheritance, because our programs will still compile,
but methods of sub class will no longer be overriding base class methods.
These methods will become like independent methods.
Cost of Inheritance
1) Execution speed
2) Program size
hashCode() :
• For every object, JVM generates a unique number which is hashcode. It
returns distinct integers for distinct objects.
• It convert the internal address of object to an integer by using an algorithm.
• Use of hashCode() method : Returns a hash value that is used to search object
in a collection which is an advantage.
• JVM uses hashcode method while saving objects into hashing related data
structures like HashSet, HashMap, Hashtable etc
equals(Object obj) :
• Compares the given object to current object (the object on which
the method is called).
• It gives a generic way to compare objects for equality.
• It is recommended to override equals(Object obj) method to get
our own equality condition on Objects.
• It is generally necessary to override the hashCode() method
whenever this method is overridden.
getClass() :
• Returns the class object of current object.
• As it is final so we don’t override it.
finalize()
• This method is called just before an object is garbage collected.
• Garbage collector destroys the unreferenced objects.
• finalize method is called just once on an object even though that
object is eligible for garbage collection multiple times.
Clone()
• Object cloning refers to creation of exact copy of an object.
• It creates a new instance of the class of current object and initializes
all its fields with exactly the contents of the corresponding fields of
this object.