Java Notes for MTE - 3 Units
Java Notes for MTE - 3 Units
E1UA307C(PP)
Introduction to Java & Its features
➢ Portable:
• As we know, java code written on one machine can be run on another
machine.
• The platform-independent feature of java in which its platform-independent
bytecode can be taken to any platform for execution makes java portable.
➢ High Performance:
• Java architecture is defined in such a way that it reduces overhead during the
runtime and at some time java uses Just In Time (JIT) compiler.
Java Programming
➢ Dynamic:
• Java being completely object-oriented gives us the flexibility to add classes,
new methods to existing classes and even create new classes through sub-
classes.
• Java even supports functions written in other languages such as C, C++ which are
referred to as native methods.
Features of Object-Oriented Programming
Object-Oriented Programming:
➢ Object-Oriented Programming is a methodology or paradigm to design a
program using classes and objects.
➢ It simplifies software development and maintenance by providing some concepts:
• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation
➢ Object:
• Any entity that has state and behavior is known as an object.
• For example, a chair, pen, table, keyboard, bike, etc. It can be physical or
logical.
Java Programming
• An Object can be defined as an instance of a class.
• An object contains an address and takes up some space in memory.
• Objects can communicate without knowing the details of each other's data or code.
• The only necessary thing is the type of message accepted and the type of response
returned by the objects.
Example:
• A dog is an object because it has states like color, name, breed, etc. as well as
behaviors like wagging the tail, barking, eating, etc.
➢ Class:
• Collection of objects is called class.
• It is a logical entity.
• A class can also be defined as a blueprint from which you can create an individual
object. Class doesn't consume any space.
Java Programming
➢ Inheritance:
• When one object acquires all the properties and behaviors of a parent
object, it is known as inheritance.
• It provides code reusability.
• It is used to achieve runtime polymorphism.
➢ Polymorphism:
• If one task is performed in different ways, it is known as
polymorphism.
• For example: to convince the customer differently, to draw something, for
example, shape, triangle, rectangle, etc.
• In Java, we use method overloading and method overriding to achieve
polymorphism.
• Another example can be to speak something;
• For example, a cat speaks meow, dog barks woof, etc.
Java Programming
➢ Abstraction:
• Hiding internal details and showing functionality is known as abstraction.
• For example: phone call, we don't know the internal processing.
• In Java, we use abstract class and interface to achieve abstraction.
➢ Encapsulation:
• Binding (or wrapping) code and data together into a single unit are
known as encapsulation.
• For example: a capsule, it is wrapped with different medicines.
• A java class is the example of encapsulation.
• Java bean is the fully encapsulated class because all the data members are
private here.
A typical structure of a Java program contains the following elements:
1. Documentation Section
2. Package Declaration
3. Import Statements
4. Interface Section
5. Class Definition
6. Class Variables and Variables
7. Main Method Class
8. Methods and Behaviors
1. Documentation Section
o The information includes the author's name, date of creation, version, program name, company
name, and description of the program. It improves the readability of the program.
o Whatever we write in the documentation section, the Java compiler ignores the statements during the
execution of the program.
o Multi-line Comment: It starts with a /* and ends with */. We write between these two symbols.
o For example:
/*It is an example of
multiline comment*/
o Documentation Comment: It starts with the delimiter (/**) and ends with */.
o For example:
/**It is an example of a documentation comment*/
Package Declaration
o For example:
1. package javatpoint; //where javatpoint is the package name
2. package com.javatpoint; //where com is the root directory and javatpoint is the subdirectory
Import Statements
o The package contains many predefined classes and interfaces.
o If we want to use any class of a particular package, we need to import that class.
o The import statement represents the class stored in the other package.
o We use the import keyword to import the class. It is written before the class declaration and after the
package statement.
o We use the import statement in two ways, either import a specific class or import all classes of a
particular package.
o In a Java program, we can use multiple import statements.
o For example:
1. import java.util.Scanner; //it imports the Scanner class only
2. import java.util.*; //it imports all the class of the java.util package
Interface Section
o It is an optional section. We can create an interface in this section if required.
o We use the interface keyword to create an interface.
o An interface is slightly different from the class. It contains only constants and method declarations.
o Another difference is that it cannot be instantiated.
o We can use interface in classes by using the implements keyword.
o An interface can also be used with other interfaces by using the extends keyword.
For example:
interface car
{
void start();
void stop();
}
Class Definition
o In this section, we define the class.
o It is a vital part of a Java program. Without the class, we cannot create any Java program.
o A Java program may contain more than one class definition.
o We use the class keyword to define the class.
o The class is a blueprint of a Java program. It contains information about user-defined methods,
variables, and constants.
o Every Java program has at least one class that contains the main() method.
For example:
class Student //class definition
{
}
Class Variables and Constants
o In this section, we define variables and constants that are to be used later in the program.
o In a Java program, the variables and constants are defined just after the class definition.
o The variables and constants store values of the parameters. It is used during the execution of the
program.
o We can also decide and define the scope of variables by using the modifiers. It defines the life of the
variables.
For example:
class Student //class definition
{
String sname; //variable
int id;
double percentage;
}
Main Method Class
o In this section, we define the main() method.
o It is essential for all Java programs. Because the execution of all Java programs starts from the main()
method.
o In other words, it is an entry point of the class. It must be inside the class.
o Inside the main method, we create objects and call the methods.
o For example:
public class Demo //class definition
{
public static void main(String args[])
{
void display()
{
System.out.println("Welcome to javatpoint");
}
//statements
}
}
When we follow and use the above elements in a Java program, the program looks like the following.
CheckPalindromeNumber.java
/*Program name: Palindrome*/
//Author's name:
/*Palindrome is number or string that will remains the same When we write that in reverse order. Some e
xample of palindrome is 393, 010, madam, etc.*/
//class definition
public class CheckPalindromeNumber
{
//main method
public static void main(String args[])
{
//variables to be used in program
int r, s=0, temp;
int x; //It is the number variable to be checked for palindrome
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number to check: ");
//reading a number from the user
x=sc.nextInt();
//logic to check if the number id palindrome or not
temp=x;
while(x>0)
{
r=x%10; //finds remainder
s=(s*10)+r;
x=x/10;
}
if(temp==s)
System.out.println("The given number is palindrome.");
else
System.out.println("The given number is not palindrome.");
}
}
Output:
Java Programming
JVM:
❖ JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it doesn't
physically exist.
❖ It is a specification that provides a runtime environment in which Java bytecode can be executed.
❖ JVMs are available for many hardware and software platforms.
❖ JVM, JRE, and JDK are platform dependent because the configuration of each OS is different
from each other.
❖ However, Java is platform independent.
❖ The JVM performs the following main tasks: Loads code, Verifies code, Executes code, Provides
runtime environment.
15
Java Programming
JRE
❖ JRE is an acronym for Java Runtime Environment.
❖ The Java Runtime Environment is a set of software tools which are used for developing Java
applications.
❖ It is used to provide the runtime environment.
❖ It is the implementation of JVM. It physically exists.
❖ It contains a set of libraries + other files that JVM uses at runtime.
16
Java Programming
JDK
❖ JDK is an acronym for Java Development Kit.
❖ The Java Development Kit (JDK) is a software development environment which is used to develop Java
applications and applets. It physically exists.
❖ It contains JRE + development tools.
❖ JDK is an implementation of any one of the below given Java Platforms released by Oracle
Corporation:
• Standard Edition Java Platform
• Enterprise Edition Java Platform
• Micro Edition Java Platform
❖ The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an
interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation generator (Javadoc),
etc. to complete the development of a Java Application.
16
Java Programming
17
Java Programming
Keywords
❖ In Java, Keywords or Reserved words are the words in a language that are used for some internal process
or represent some predefined actions.
❖ These words are therefore not allowed to use as variable names or objects.
18
Java Programming
19
Java Programming
20
Java Programming
21
Java Programming
22
Java Programming
23
Java Programming
24
Java Programming
24
Java Programming
Java Variable:
❖ A variable is a container which holds the value while the Java program is executed.
❖ A variable is assigned with a data type.
❖ Variable is a name of memory location.
Variable:
❖ A variable is the name of a reserved area allocated in memory. In other words, it is a name of the
memory location.
❖ It is a combination of "vary + able" which means its value can be changed.
25
Java Programming
How to Declare Variables in Java?
❖We can declare variables in Java as pictorially depicted below as a visual aid.
26
Java Programming
27
Java Programming
28
Java Programming
29
Java Programming
Example:
30
Java Programming
Widening:
Narrowing (Typecasting):
31
Java Programming
Overflow:
32
Java Programming
❖Data types specify the different sizes and values that can be stored in the variable.
❖There are two types of data types in Java:
33
1
Java Programming
1. Primitive Data Types:
❖Primitive data are only single values and have no special capabilities.
❖There are 8 primitive data types:
34
Java Programming
1. Boolean Data Type:
❖The Boolean data type is used to store only two possible values: true and false. This data type is used for
simple flags that track true/false conditions.
❖The Boolean data type specifies one bit of information, but its "size" can't be defined precisely.
35
Java Programming
3. Short Data Type:
❖The short data type is a 16-bit signed two’s complement integer.
❖Similar to byte, use a short to save memory in large arrays, in situations where the memory savings actually
matters.
36
Java Programming
5. Long Data Type:
❖The range of a long is quite large. The size of the Long Datatype is 8 bytes (64 bits).
37
Java Programming
❖ The char data type is a single 16-bit Unicode character with the size of 2 bytes (16 bits).
38
Java Programming
39
Java Programming
40
Java Programming
2. Non-Primitive Data Type or Reference Data Types:
❖The Reference Data Types will contain a memory address of variable values.
❖Because the reference types won’t store the variable value directly in memory.
❖They are strings, objects, arrays, etc.
1. Strings:
❖Strings are defined as an array of characters.
❖The difference between a character array and a string in Java is,
• The string is designed to hold a sequence of characters in a single variable whereas, a character array is a
collection of separate char-type entities.
❖Unlike C/C++, Java strings are not terminated with a null character.
41
Java Programming
2. Class:
❖ A class is a user-defined blueprint or prototype from which objects are created.
❖ It represents the set of properties or methods that are common to all objects of one type.
❖ In general, class declarations can include these components, in order:
1. Modifiers : A class can be public or has default access. Refer to access specifiers for classes or interfaces in Java
2. Class name: The name should begin with an initial letter (capitalized by convention).
3. Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the keyword extends. A class
can only extend (subclass) one parent.
4. Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any, preceded by the
keyword implements. A class can implement more than one interface.
5. Body: The class body is surrounded by braces, { }. 42
Java Programming
3. Object:
❖An Object is a basic unit of Object-Oriented Programming and represents real-life entities.
❖A typical Java program creates many objects, which as you know, interact by invoking methods.
❖An object consists of :
• State: It is represented by the attributes of an object. It also reflects the properties of an object.
• Behavior: It is represented by the methods of an object. It also reflects the response of an object to other
objects.
• Identity: It gives a unique name to an object and enables one object to interact with other objects.
4. Interface:
❖ Like a class, an interface can have methods and variables, but the methods declared in an interface are by
default abstract (only method signature, no body).
• A Java library example is Comparator Interface. If a class implements this interface, then it can be
used to sort a collection.
5. Array:
❖ An Array is a group of like-typed variables that are referred to by a common name.
❖ In Java, all arrays are dynamically allocated.
43
Java Programming
Operators-Expression:
❖Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.
❖ They are classified based on the functionality they provide.
1. Arithmetic Operators : +, - / , %
2. Unary Operators: - , !, ++, --, ~
3. Assignment Operator: =, +=, -=, *=, /=, %=
4. Relational Operators: = = , !=, >, <, >=, <=,
5. Logical Operators: &&, ||, !
6. Ternary Operator
7. Bitwise Operators: |, &, ^, ~ (OR, AND, XOR, Complement)
8. Shift Operators
1. Arithmetic Operators:
❖These operators involve the mathematical operators that can be used to perform various simple or
advanced arithmetic operations on the primitive data types referred to as the operands.
❖These operators consist of various unary and binary operators that can be applied on a single or two
operands.
44
Java Programming
45
Java Programming
46
Java Programming
47
Java Programming
An example program for all basic arithmetic operators:
48
Java Programming
2. Unary Operators:
❖The Java unary operators require only one operand. Unary operators are used to perform various
operations,
1. Incrementing/decrementing a value by one
2. Negating an expression
3. Inverting the value of a boolean
1. Unary minus(-):
49
Java Programming
50
Java Programming
51
Java Programming
52
Java Programming
53
Java Programming
54
Java Programming
55
Java Programming
56
Java Programming
3. Assignment Operators:
❖These operators are used to assign values to a variable.
❖The left side operand of the assignment operator is a variable, and the right side operand of
the assignment operator is a value.
❖The value on the right side must be of the same data type of the operand on the left side.
Otherwise, the compiler will raise an error.
❖This means that the assignment operators have right to left associativity, i.e., the value given on
the right-hand side of the operator is assigned to the variable on the left.
❖Therefore, the right-hand side value must be declared before using it or should be a constant.
❖The general format of the assignment operator is,
58
Java Programming
59
Java Programming
60
Java Programming
61
Java Programming
62
Java Programming
63
Java Programming
4. Relational Operators:
❖A bunch of binary operators used to check for relations between two operands, including equality, greater
than, less than, etc.
❖They return a boolean result after the comparison and are extensively used in looping statements as well as
conditional if-else statements and so on.
❖ The general format of representing relational operator is:
64
Java Programming
65
Java Programming
66
Java Programming
67
Java Programming
68
Java Programming
69
Java Programming
70
Java Programming
5. Logical Operators:
❖Logical operators are used to perform logical “AND”, “OR” and “NOT” operations, i.e. the function similar
to AND gate and OR gate in digital electronics.
❖They are used to combine two or more conditions/constraints or to complement the evaluation of the original
condition under particular consideration.
❖One thing to keep in mind is, while using AND operator, the second condition is not evaluated if the first
one is false.
❖Where as while using OR operator, the second condition is not evaluated if the first one is true, i.e. the AND
and OR operators have a short-circuiting effect.
❖Used extensively to test for several conditions for making a decision.
1. AND Operator ( && ) – if( a && b ) [if true execute else don’t]
71
Java Programming
Example For Logical Operator :
❖Here is an example depicting all the operators where the values of variables a, b, and c are kept the same for
all the situations.
72
Java Programming
73
Java Programming
74
Java Programming
75
Java Programming
6. Ternary Operator:
❖Java ternary operator is the only conditional operator that takes three operands.
❖It’s a one-liner replacement for the if-then-else statement and is used a lot in Java programming.
76
Java Programming
77
Java Programming
Example:
78
Java Programming
7. Bitwise Operators:
❖Bitwise operators are used to performing the manipulation of individual bits of a number.
❖They can be used with any integral type (char, short, int, etc.).
❖They are used when performing update and query operations of the Binary indexed trees.
79
Java Programming
80
Java Programming
81
Java Programming
82
Java Programming
8. Shift Operator:
❖By shifting the bits of its first operand right or left, a shift operator performs bit manipulation on data.
83
Java Programming
84
Java Programming
85
Control Structures:
❖ In java, the selection statements are also known as decision making statements or branching statements.
❖ The selection statements are used to select a part of the program to be executed based on a condition.
❖ Java provides the following selection statements.
1. if statement
2. if-else statement
3. if-else if statement
4. nested if statement
5. switch statement
1) Simple if statement:
❖ In Java, we use the if statement to test a condition and decide the execution of a block of statements based on that condition result.
❖ If the condition is True, then the block of statements is executed and if it is False, then the block of statements is ignored.
❖ The syntax and execution flow of if the statement is as follows.
EX: Student.java
public class Student
{
public static void main(String[] args)
{
int x = 10;
int y = 12;
if(x+y > 20)
{
System.out.println("x + y is greater than 20");
}
}
}
❖ The if-else statement is an extension to the if-statement, which uses another block of code, i.e., else block.
❖ The else block is executed if the condition of the if-block is evaluated as false.
Ex: Student.java
public class Student
{
public static void main(String[] args)
{
int x = 10;
int y = 12;
if(x+y < 10)
{
System.out.println("x + y is less than 10");
}
else
{
System.out.println("x + y is greater than 20");
}
}
}
if(condition 1)
{
statement 1; //executes when condition 1 is true
}
else if(condition 2)
{
statement 2; //executes when condition 2 is true
}
else
{
statement 3; //executes when all the conditions are false
}
Ex: Student.java
public class Student
{
public static void main(String[] args)
{
String city = "Delhi";
if(city == "Meerut")
{
System.out.println("city is meerut");
}
else if (city == "Noida")
{
System.out.println("city is noida");
}
else if(city == "Agra")
{
System.out.println("city is agra");
}
else
{
System.out.println(city);
}
}
} Output: Delhi
4. Nested if statement:
❖ Writing an if statement inside another if-statement is called nested if statement.
❖ The general syntax of the nested if-statement is as follows.
if(condition 1)
{
statement 1; //executes when condition 1 is true
if(condition 2)
{
statement 2; //executes when condition 2 is true
}
else
{
statement 3; //executes when condition 2 is false
}
}
Ex: Student.java
class Nestedif
{
public static void main(String args[])
{
int a=10;
int b=20;
if(a==10){
if(b==20){
System.out.println("Nested If example");
}
}
}
}
5. Switch statement:
❖ In Java, Switch statements are similar to if-else-if statements.
❖ The switch statement contains multiple blocks of code called cases and a single case is executed based on the variable which is being
switched.
❖ The switch statement is easier to use instead of if-else-if statements. It also enhances the readability of the program.
Points to be noted about switch statement:
➢ The case variables can be int, short, byte, char, or enumeration. String type is also supported since version 7 of Java
➢ Cases cannot be duplicate.
➢ Default statement is executed when any of the case doesn't match the value of expression. It is optional.
➢ Break statement terminates the switch block when the condition is satisfied. It is optional, if not used, next case is executed.
➢ While using switch statements, we must notice that the case expression will be of the same type as the variable. However, it will
also be a constant value.
Ex: Student.java
public class Student implements Cloneable
{
public static void main(String[] args)
{
int num = 2;
switch (num)
{
case 0:
System.out.println("number is 0");
break;
case 1:
System.out.println("number is 1");
break;
default:
System.out.println(num);
}
}
}
Output: 2
2. Iterative Control Statements:
❖ In programming, sometimes we need to execute the block of code repeatedly while some condition evaluates to true.
❖ However, loop statements are used to execute the set of instructions in a repeated order.
❖ The execution of the set of instructions depends upon a particular condition.
❖ In Java, we have three types of loops that execute similarly.
1. for loop
2. while loop
3. do-while loop
1. for loop:
❖ In Java, for loop is similar to C and C++.
❖ It enables us to initialize the loop variable, check the
condition, and increment/decrement in a single line of
code.
❖ We use the for loop only when we exactly know the
number of times, we want to execute the block of code.
EX: Calculation.java
public class Calculattion
{
public static void main(String[] args)
{
int sum = 0;
for(int j = 1; j<=10; j++) {
sum = sum + j;
}
System.out.println("The sum of first 10 natural numbers is " + sum);
}
}
Ex: Calculation.java
public class Calculation
{
public static void main(String[] args)
{
String[] names = {"Java","C","C++","Python","JavaScript"};
System.out.println("Printing the content of the array names:\n");
for(String name:names)
{
System.out.println(name);
}
}
}
Output:
Printing the content of the array names:
Java
C
C++
Python
JavaScript
2. while loop:
❖ The while loop is also used to iterate over the number of statements multiple times.
❖ However, if we don't know the number of iterations in advance, it is recommended to use a while loop.
❖ Unlike for loop, the initialization and increment/decrement doesn't take place inside the loop statement in while loop.
❖ It is also known as the entry-controlled loop since the condition is checked at the start of the loop.
❖ If the condition is true, then the loop body will be executed; otherwise, the statements after the loop will be executed.
Ex: Calculation .java
public class Calculation
{
public static void main(String[] args)
{
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
while(i<=10)
{
System.out.println(i);
i = i + 2;
}
}
}
Output:
3. do-while loop
❖ The do-while loop checks the condition at the end of the loop after executing the loop statements.
❖ When the number of iteration is not known and we have to execute the loop at least once, we can use do-while loop.
❖ It is also known as the exit-controlled loop since the condition is not checked in advance.
1. break:
❖ As the name suggests, the break statement is used to break the current flow of the program and transfer the control to the next
statement outside a loop or switch statement.
❖ However, it breaks only the inner loop in the case of the nested loop.
❖ The break statement cannot be used independently in the Java program, i.e., it can only be written inside the loop or switch
statement.
The following picture depicts the execution flow of the break statement:
❖
Ex: Consider the following example in which we have used the break statement with the for loop:
❖ Unlike break statement, the continue statement doesn't break the loop,
❖ whereas, it skips the specific part of the loop and jumps to the next iteration of the loop immediately.
❖
❖ Consider the following example to understand the functioning of the continue statement in Java.
Type casting:
Converting a lower data type into a higher one is called widening type
casting.
import java.io.*;
class GFG {
public static void main(String[] args)
{
int i = 10;
// Wideing TypeCasting (Automatic Casting)from int to long
long l = i;
// Wideing TypeCasting (Automatic Casting)from int to double
double d = i;
System.out.println("Integer: " + i);
System.out.println("Long: " + l);
System.out.println("Double: " + d);
}
}
Output:
Integer: 10
Long: 10
Double: 10.0
The process of downsizing a bigger data type into a smaller one is known as
narrowing type casting.
Casting up or explicit type casting are other names for it.
It doesn’t just happen by itself. If we don’t explicitly do that, a compile-time
error will occur.
Narrowing type casting is unsafe because data loss might happen due to the
lower data type’s smaller range of permitted values.
A cast operator assists in the process of explicit casting.
// Java Program to demonstrate Narrow type casting
import java.io.*;
class GFG {
public static void main(String[] args)
{
double i = 100.245;
Output:
1. Explicit Upcasting
2. Explicit Downcasting
1. Explicit Upcasting:
import java.io.*;
class Animal {
public void makeSound()
{
System.out.println("The animal makes a sound");
}
}
class Dog extends Animal {
public void makeSound()
{
System.out.println("The dog barks");
}
public void fetch()
{
System.out.println("The dog fetches a ball");
}
}
class GFG {
public static void main(String[] args)
{
// Upcasting
Animal animal = new Dog();
// Calls the overridden method in Dog class
animal.makeSound();
// This would give a compile error as fetch() is not a method in
Animal class animal.fetch();
}
}
Output:
2. Explicit Downcasting:
When a subclass type refers to an object of the parent class, the process is
referred to as downcasting.
If it is done manually, the compiler issues a runtime ClassCastException
error. It can only be done by using the instanceof operator.
Only the downcast of an object that has already been upcast is possible.
// Java Program to demonstrate Explicit downcasting
import java.io.*;
class Animal {
public void eat()
{
System.out.println("The animal is eating.");
}
}
class Cat extends Animal {
public void meow()
{
System.out.println("The cat is meowing.");
}
}
class GFG {
public static void main(String[] args)
{
Animal animal = new Cat();
animal.eat();
// Explicit downcasting
Cat cat = (Cat)animal;
cat.meow();
}
}
Output:
Classes:
❖ A class in Java is a set of objects which shares common characteristics/ behavior and common properties/ attributes.
❖ It is a user-defined blueprint or prototype from which objects are created.
❖ Ex: Student is a class while a particular student named Ravi is an object.
Properties of Classes:
1. Class is not a real-world entity. It is just a template or blueprint or prototype from which objects are created.
2. Class does not occupy memory.
3. Class is a group of variables of different data types and group of methods.
4. A Class can contain:
❖ Data member
❖ Method
❖ Constructor
❖ Nested Class
❖ Interface
Class Declaration:
// Java Program for class example
class Student {
// data member (also instance variable)
int id;
// data member (also instance variable)
String name;
public static void main(String args[])
{
// creating an object of Student
Student s1 = new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}
Output:
0
null
Components of Java Classes:
Objects:
❖ Objects are the instances of a class that are created to use the attributes and methods of a class.
❖ A typical Java program creates many objects, which as you know, interact by invoking methods.
❖ An object consists of :
1. State: It is represented by attributes of an object. It also reflects the properties of an object.
2. Behavior: It is represented by the methods of an object. It also reflects the response of an object with other objects.
3. Identity: It gives a unique name to an object and enables one object to interact with other objects.
Create an Object:
❖ In Java, an object is created from a class. We have already created the class named Add, so now we can use this to create objects.
❖ To create an object of Add, specify the class name, followed by the object name, and use the keyword new:
Example:
Create an object called "myObj" and print the value of x:
int x = 5;
System.out.println(myObj.x);
}}
Output:
5
Multiple Objects:
❖ You can create multiple objects of one class:
Example:
int x = 5;
System.out.println(myObj1.x);
System.out.println(myObj2.x);
Output:
5
5
Difference between Java Class and Objects:
Class Object
No memory is allocated when a class is declared. Memory is allocated as soon as an object is created.
A class can only be declared once. Objects can be created many times as per requirement.
Method Declaration:
For example:
a. Predefined Method
b. User-defined Method
A. Predefined Method:
class Demo
{
public static void main(String[] args)
{
// using the max() method of Math class
System.out.print("The maximum number is: " + Math.
max(9,7));
}
}
Output:
The maximum number is: 9
B. User-defined Method:
import java.util.Scanner;
public class EvenOdd
{
public static void main (String args[])
{
//creating Scanner class object
Scanner scan=new Scanner(System.in);
System.out.print("Enter the number: ");
//reading value from the user
int num=scan.nextInt();
//method calling
findEvenOdd(num);
}
❖ In the above code snippet, as soon as the compiler reaches at
line findEvenOdd(num), the control transfer to the method and
gives the output accordingly.
Ex: Addition.java
Output:
Example: Display.java
Output:
Example:
public class InstanceMethodExample
{
public static void main(String [] args)
{
//Creating an object of the class
InstanceMethodExample obj = new InstanceMethodExample()
;
//invoking instance method
System.out.println("The sum is: "+obj.add(12, 13));
}
int s;
//userdefined method because we have not used static keyword
Output:
Syntax:
Ex: Demo.java
Output:
Abstract method...
Constructors
Here,
❖ Test() is a constructor. It has the same name as that of the class
and doesn't have a return type.
❖
Example:
class Cons {
private String name;
// constructor
Cons() {
System.out.println("Constructor Called:");
name = "Prajesh";
}
2. Parameterized Constructor
3. Default Constructor
1. No-Arg Constructors:
❖ Similar to methods, a Java constructor may or may not have any
parameters (arguments).
For example,
private Constructor()
{
// body of the constructor
}
For example: Java Private No-arg Constructor
class Main {
int i;
// constructor with no parameter
private Main() {
i = 5;
System.out.println("Constructor is called");
}
public static void main(String[] args) {
// calling the constructor without any parameter
Main obj = new Main();
System.out.println("Value of i: " + obj.i);
}
}
Output:
Constructor is called
Value of i: 5
class Company {
String name;
// public constructor
public Company() {
name = "Prabha";
}
}
class Main {
public static void main(String[] args) {
// object is created in another class
Company obj = new Company();
System.out.println("Company name = " + obj.name);
}
}
Output:
class Main {
String languages;
// constructor accepting single value
Main(String lang) {
languages = lang;
System.out.println(languages + " Programming Language");
}
public static void main(String[] args) {
// call constructor by passing a single value
Main obj1 = new Main("Java");
Main obj2 = new Main("Python");
Main obj3 = new Main("C");
}
}
Output:
3. Default Constructor:
class Main {
int a;
boolean b;
System.out.println("Default Value:");
System.out.println("a = " + obj.a);
System.out.println("b = " + obj.b);
}
}
Output:
Default Value:
a = 0
b = false
boolean false
byte 0
short 0
int 0
long 0L
char \u0000
float 0.0f
double 0.0d
❖ In Java, two or more methods may have the same name if they
differ in parameters (different number of parameters, different
types of parameters, or both).
❖ These methods are called overloaded methods and this feature is
called method overloading.
For example:
class MethodOverloading {
private static void display(int a){
System.out.println("Arguments: " + a);
}
Arguments: 1
Arguments: 1 and 4
2. Method Overloading by changing the data type of parameters:
class MethodOverloading {
class HelperService {
Output:
500
89.993
550.00
Important Points
❖ Two or more methods can have the same name inside the
same class if they accept different arguments. This feature is
known as method overloading.
this – keyword:
1. In Java, this is a reference variable that refers to the current
object.
❖ The this keyword can be used to refer current class instance variable.
❖ If there is ambiguity between the instance variables and parameters, this
keyword resolves the problem of ambiguity.
Ex: The example, parameters (formal arguments) and instance variables are
same. So, we are using this keyword to distinguish local variable and
instance variable.
class Student
{
int rollno;
String name;
float fee;
class TestThis2
{
public static void main(String args[])
{
Student s1=new Student(111,"Raja",7000f);
Student s2=new Student(112,"Praba",9000f);
s1.display();
s2.display();
}
}
Output:
Program:
class A{
void n(){
System.out.println("hello n");
//m();//same as this.m()
this.m();
}
}
class TestThis4{
public static void main(String args[]){
A a=new A();
a.n();
}}
Output:
hello n
hello m
❖ The this() constructor call can be used to invoke the current class
constructor.
❖ It is used to reuse the constructor. In other words, it is used for
constructor chaining.
Output:
hello a
10
4) this: to pass as an argument in the method
Example:
class S2{
void p(){
m(this);
}
public static void main(String args[]) {
S2 s1 = new S2();
s1.p();
}
}
Output:
method is invoked
5) this: to pass as argument in the constructor call
❖ We can pass the this keyword in the constructor also. It is useful if we
have to use one object in multiple classes.
Example:
class B
{
A4 obj;
B(A4 obj) {
this.obj=obj;
}
void display(){
System.out.println(obj.data);//using data member of A4 class
}
}
class A4
{
int data=10;
A4( )
{
B b=new B(this);
b.display();
}
public static void main(String args[])
{
A4 a=new A4();
}
}
Output: 10
6). This: keyword can be used to return current class
instance
❖ We can return this keyword as an statement from the method.
❖ In such case, return type of the method must be the class type (non-
primitive).
Example: of this keyword that you return as a statement from the method
class A
{
A getA() {
return this; }
void msg(){System.out.println("Hello java");
}
}
class Test1{
public static void main(String args[])
{ new A().getA().msg();
}
}
Output:
Hello java
static keyword:
Advantages:
//constructor
Student(int r, String n){
rollno = r;
name = n;
}
//we can change the college of all objects by the single line of code
Student.college="BBDIT";
s1.display();
s2.display();
}
}
Output:
111 Karan ITS
222 Aryan ITS
2) Java static method:
❖ There are two main restrictions for the static method. They are:
1. The static method can not use non-static data member or call
non-static method directly.
2. this and super cannot be used in static context.
Ex:
class A{
int a=40; //non static
public static void main(String args[]){
System.out.println(a); } }
Output:
Compile Time Error
Why is the Java main method static?
Example:
class A2{
static{System.out.println("static block is invoked");}
public static void main(String args[]){
System.out.println("Hello main");
} }
Output:
static block is invoked
Hello main
Arrays
Java Arrays:
❖ Normally, an array is a collection of similar type of elements which has
contiguous memory location.
❖ Java array is an object which contains elements of a similar data type.
Additionally, the elements of an array are stored in a contiguous memory
location.
❖ It is a data structure where we store similar elements. We can store only a
fixed set of elements in a Java array.
❖ Array in Java is index-based, the first element of the array is stored at the
0th index, 2nd element is stored on 1st index and so on.
❖ Unlike C/C++, we can get the length of the array using the length member.
In C/C++, we need to use the sizeof operator.
❖ In Java, array is an object of a dynamically generated class.
❖ Java array inherits the Object class.
❖ We can store primitive values or objects in an array in Java.
❖ Like C/C++, we can also create single dimentional or multidimentional arrays
in Java.
❖ Moreover, Java provides the feature of anonymous arrays which is not
available in C/C++.
Advantages:
❖ Code Optimization: It makes the code optimized, we can retrieve or sort
the data efficiently.
❖ Random access: We can get any data located at an index position.
Disadvantages:
❖ Size Limit: We can store only the fixed size of elements in the array. It
doesn't grow its size at runtime. To solve this problem, collection
framework is used in Java which grows automatically.
Types of Array:
❖ There are two types of array.
1. Single Dimensional Array
2. Multidimensional Array
Instantiation of an Array:
❖ Simple example of java array, where we are going to declare, instantiate, initialize
and traverse an array.
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
Output:
Declaration, Instantiation and Initialization of Array:
❖ We can declare, instantiate and initialize the java array together by:
Output:
For-each Loop:
❖ We can also print the Java array using for-each loop.
❖ The Java for-each loop prints the array elements one by one.
❖ It holds an array element in a variable, then executes the body of the loop.
Output:
Output:
Anonymous Array:
❖ Java supports the feature of an anonymous array, so you don't need to declare
the array while passing an array to the method.
Output:
2. Multidimensional Array:
❖ In such case, data is stored in row and column based index (also known as
matrix form).
Output:
Jagged Array in Java:
❖ If we are creating odd number of columns in a 2D array, it is known as a
jagged array.
❖ In other words, it is an array of arrays with different number of columns.
Output:
Addition of 2 Matrices:
Output:
Multiplication of 2 Matrices:
❖ In the case of matrix multiplication, a one-row element of the first matrix is
multiplied by all the columns of the second matrix which can be understood by
the image given below.
❖ A simple example to multiply two matrices of 3 rows and 3 columns.
Output:
String
❖ A string is a sequence of characters surrounded by double
quotations.
❖ In a java programming language, a string is the object of a built-in class
String.
❖ In the background, the string values are organized as an array of a
character data type.
❖ The string created using a character array can not be extended. It does
not allow to append more characters after its definition, but it can be
modified.
Let's look at the following example java code.
Example:
Output:
Difference between Array and String:
Array can hold any of the data But, the String can hold only a char
02.
types. data type.
06. The length of the array is fixed. The size of the string is not fixed.
String Buffer-String Handling Mechanism
StringBuffer Class:
Java StringBuffer class is used to create mutable (modifiable) String
objects.
The StringBuffer class in Java is the same as String class except it
is mutable i.e. it can be changed.
StringBuffer() It creates an empty String buffer with the initial capacity of 16.
public
delete(int startIndex, It is used to delete the string from specified
synchronized
int endIndex) startIndex and endIndex.
StringBuffer
public
synchronized reverse() is used to reverse the string.
StringBuffer
substring(int
It is used to return the substring from the
public String beginIndex, int
specified beginIndex and endIndex.
endIndex)
Example:
class StringBufferExample2
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java"); //now original string is changed
System.out.println(sb); //prints HJavaello
}
}
Output: HJavaello
Output: HJavalo
Example:
class StringBufferExample4
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}
Output: Hlo
5) StringBuffer reverse() Method:
The reverse() method of the StringBuilder class reverses the
current String.
Example:
class StringBufferExample5
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}
Output: olleH
Example:
class StringBufferExample6
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
}
}
Output:
16
16
34
Example:
class StringBufferExample7
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
sb.ensureCapacity(10);//now no change
System.out.println(sb.capacity());//now 34
sb.ensureCapacity(50);//now (34*2)+2
System.out.println(sb.capacity());//now 70
}
}
Output:
16
16
34
34
70
Wrapper Classes and Command line arguments
Wrapper Classes:
➢ A Wrapper class in Java is a class whose object wraps or contains primitive
data types.
➢ When we create an object to a wrapper class, it contains a field and in this field,
we can store primitive data types.
➢ The wrapper class in Java provides the mechanism to convert primitive
data types into object and object into primitive data types.
1. They convert primitive data types into objects. Objects are needed if
we wish to modify the arguments passed into a method (because primitive
types are passed by value).
333
//Printing objects
System.out.println("---Printing object values---");
System.out.println("Byte object: "+byteobj);
System.out.println("Short object: "+shortobj);
System.out.println("Integer object: "+intobj);
System.out.println("Long object: "+longobj);
System.out.println("Float object: "+floatobj);
System.out.println("Double object: "+doubleobj);
System.out.println("Character object: "+charobj);
System.out.println("Boolean object: "+boolobj);
//Printing primitives
System.out.println("---Printing primitive values---");
System.out.println("byte value: "+bytevalue);
System.out.println("short value: "+shortvalue);
System.out.println("int value: "+intvalue);
System.out.println("long value: "+longvalue);
System.out.println("float value: "+floatvalue);
System.out.println("double value: "+doublevalue);
System.out.println("char value: "+charvalue);
System.out.println("boolean value: "+boolvalue);
}
}
Output:
class CommandLineExample
{
public static void main(String args[])
{
System.out.println("Your first argument is: "+args[0]);
}
}
Compile by > javac CommandLineExample.java
Run by > java CommandLineExample sonoo
➢ In this example, we are printing all the arguments passed from the command-
line.
➢ For this purpose, we have traversed the array using for loop.
class A
{
public static void main(String args[])
{
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
}
}
Compile by > javac A.java
Run by > java A sonoo jaiswal 1 3 abc
Output:
sonoo
jaiswal
1
3
abc
Java API Packages
Java Package:
➢ A Java package is a group of similar types of classes, interfaces and
sub-packages.
➢ Package in java can be categorized in two form, built-in package and
user-defined package.
➢ There are many built-in packages such as java, lang, awt, javax, swing,
net, io, util, sql, etc.
Advantages:
1) The Java package is used to categorize the classes and interfaces to
be easily maintained.
2) The Java package provides access protection.
3) The Java package removes naming collision.
A simple example of a Java package:
➢ The package keyword is used to create a package in java.
//save as Simple.java
package mypack;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}
How to compile Java package
➢ syntax is given below:
javac -d directory javafilename
For example:
javac -d . Simple.java
Note:
• The -d switch specifies the destination where to put the generated
class file.
• You can use any directory name like /home (in case of Linux), d:/abc
(in case of windows), etc.
• If you want to keep the package within the same directory, you can
use it. (dot).
• The -d is a switch that tells the compiler where to put the class file
i.e. it represents destination. The . represents the current folder.
How to run the java package program
➢ You need to use fully qualified name e.g. mypack.Simple etc to run the
class.
To Compile: javac -d . Simple.java
To Run: java mypack.Simple
Output: Hello
2) Using packagename.classname
➢ If you import package.classname then only declared class of this
package will be accessible.
//save by B.java
package mypack;
import pack.A;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
Output: Hello
3) Using fully qualified name
➢ If you use fully qualified name then only declared class of this
package will be accessible.
➢ Now there is no need to import. But you need to use fully qualified
name every time when you are accessing the class or interface.
➢ It is generally used when two packages have same class name e.g.
java.util and java.sql packages contain Date class.
//save by A.java
package pack;
public class A
{
public void msg(){System.out.println("Hello");
}
}
//save by B.java
package mypack;
class B
{
public static void main(String args[])
{
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
Output: Hello
Note: If you import a package, subpackages will not be imported.
Note: Sequence of the program must be package then import then class.
Subpackage in Java:
➢ Package inside the package is called the subpackage. It should be
created to categorize the package further.
➢ Let's take an example, Sun Microsystem has definded a package
named java that contains many classes like System, String, Reader,
Writer, Socket etc.
➢ These classes represent a particular group e.g. Reader and Writer
classes are for Input/Output operation, Socket and ServerSocket
classes are for networking etc and so on.
➢ So, Sun has subcategorized the java package into subpackages such
as lang, net, io etc. and put the Input/Output related classes in io
package, Server and ServerSocket classes in net packages and so on.
Note: The standard of defining package is domain.company.package e.g.
com.javatpoint.bean or org.sssit.dao.
Example of Subpackage:
package com.javatpoint.core;
class Simple
{
public static void main(String args[])
{
System.out.println("Hello subpackage");
}
}
For example:
//save as Simple.java
package mypack;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}
To Compile:
e:\sources> javac -d c:\classes Simple.java
To Run:
➢ To run this program from e:\source directory, you need to set classpath
of the directory where the class file resides.
e:\sources> set classpath=c:\classes;.;
e:\sources> java mypack.Simple
Another way to run this program by -classpath switch of java:
➢ The -classpath switch can be used with javac and java tool.
➢ To run this program from e:\source directory, you can use -classpath
switch of java that tells where to look for class file.
For example:
e:\sources> java -classpath c:\classes mypack.Simple
Rule: There can be only one public class in a java source file and it must be
saved by the public class name.
//save as C.java otherwise Compilte Time Error
class A
{
}
class B
{
}
public class C
{
}
Basics of Inheritance - Forms of Inheritance
Inheritance:
➢ Inheritance is a mechanism of driving a new class from an existing class.
The existing (old) class is known as base class or super class or parent
class.
➢ The new class is known as a derived class or sub class or child class. It
allows us to use the properties and behavior of one class (parent) in another
class (child).
➢ A class whose properties are inherited is known as parent class and a
class that inherits the properties of the parent class is known as child class.
➢ Thus, it establishes a relationship between parent and child class that
is known as parent-child or Is-a relationship.
➢ Suppose, there are two classes named Father and Child and we want to
inherit the properties of the Father class in the Child class.
➢ We can achieve this by using the extends keyword.
Points to Remember:
Example: Executive.java
class Employee
{
float salary=34534*12;
}
public class Executive extends Employee
{
float bonus=3000*6;
public static void main(String args[])
{
Executive obj=new Executive();
System.out.println("Total salary credited: "+obj.salary);
System.out.println("Bonus of six months: "+obj.bonus);
}
}
Output:
In the above figure, the class Marks inherits the members or methods of
the class Students. The class Sports inherits the members of the class
Marks.
Therefore, the Student class is the parent class of the class Marks and the
class Marks is the parent of the class Sports.
Hence, the class Sports implicitly inherits the properties of the Student
along with the class Marks.
Example: MultilevelInheritanceExample.java
//super class
class Student
{
int reg_no;
void getNo(int no)
{
reg_no=no;
}
void putNo()
{
System.out.println("registration number= "+reg_no);
}
}
//intermediate sub class
class Marks extends Student
{
float marks;
void getMarks(float m)
{
marks=m;
}
void putMarks()
{
System.out.println("marks= "+marks);
}
}
//derived class
class Sports extends Marks
{
float score;
void getScore(float scr)
{
score=scr;
}
void putScore()
{
System.out.println("score= "+score);
}
}
public class MultilevelInheritanceExample
{
public static void main(String args[])
{
Sports ob=new Sports();
ob.getNo(0987);
ob.putNo();
ob.getMarks(78);
ob.putMarks();
ob.getScore(68.7);
ob.putScore();
}
}
Output:
In the above figure, the classes Science, Commerce, and Arts inherit a single
parent class named Student.
Example: HierarchicalInheritanceExample.java
//parent class
class Student
{
public void methodStudent()
{
System.out.println("The method of the class Student invoked.");
}
}
class Science extends Student
{
public void methodScience()
{
System.out.println("The method of the class Science invoked.");
}
}
class Commerce extends Student
{
public void methodCommerce()
{
System.out.println("The method of the class Commerce invoked.");
}
}
class Arts extends Student
{
public void methodArts()
{
System.out.println("The method of the class Arts invoked.");
}
}
public class HierarchicalInheritanceExample
{
public static void main(String args[])
{
Science sci = new Science();
Commerce comm = new Commerce();
Arts art = new Arts();
//all the sub classes can access the method of super class
sci.methodStudent();
comm.methodStudent();
art.methodStudent();
}
}
Output:
In the below figure, GrandFather is a super class. The Father class inherits
the properties of the GrandFather class.
I am daughter.
Multiple Inheritance (not supported):
➢ Java does not support multiple inheritances due to ambiguity. For
example, consider the following Java program.
Example: Demo.java
class Wishes
{
void message()
{
System.out.println("Best of Luck!!");
}
}
class Birthday
{
void message()
{
System.out.println("Happy Birthday!!");
}
}
public class Demo extends Wishes, Birthday //considering a sce
nario
{
public static void main(String args[])
{
Demo obj=new Demo();
//can't decide which classes' message() method will be invoked
obj.message();
}
}
Output:
The above code gives error because the compiler cannot decide which
message() method is to be invoked. Due to this reason, Java does not
support multiple inheritances at the class level but can be achieved through
an interface.
Super keyword – Final Keywords, Method Overriding
Super keyword:
➢ The super keyword in Java is a reference variable that refers to the immediate parent
class object.
➢ Whenever you create the instance of a subclass, an instance of parent class is
created implicitly which is referred by super reference variable.
Example:
class Animal
{
String color="white";
}
class Dog extends Animal
{
String color="black";
void printColor()
{
System.out.println(color); //prints color of Dog class
System.out.println(super.color); //prints color of Animal class
} }
class TestSuper1
{
public static void main(String args[])
{
Dog d=new Dog();
d.printColor();
}}
Output:
black
white
Note: In the above example, Animal and Dog both classes have a common
property color. If we print color property, it will print the color of current class by
default. To access the parent property, we need to use super keyword.
➢ The super keyword can also be used to invoke parent class method.
➢ It should be used if the subclass contains the same method as parent
class. In other words, it is used if the method is overridden.
Example:
class Animal
{
void eat()
{
System.out.println("eating...");
} }
class Dog extends Animal
{
void eat(){System.out.println("eating bread...");
}
void bark()
{
System.out.println("barking...");
}
void work()
{
super.eat();
bark();
} }
class TestSuper2
{
public static void main(String args[])
{
Dog d=new Dog();
d.work();
} }
Output:
eating...
barking...
Note: In the above example Animal and Dog both classes have eat() method
if we call eat() method from Dog class, it will call the eat() method of Dog class
by default because priority is given to local.
➢ The super keyword can also be used to invoke the parent class
constructor.
Example:
class Animal
{
Animal()
{
System.out.println("animal is created");
} }
class Dog extends Animal
{
Dog()
{
super();
System.out.println("dog is created");
} }
class TestSuper3
{
public static void main(String args[])
{
Dog d=new Dog();
}}
Output:
animal is created
dog is created
Note: super() is added in each class constructor automatically by compiler if
there is no super() or this().
Output:
animal is created
dog is created
Final Keywords:
➢ The final keyword in Java is used to restrict the user. The Java final keyword
can be used in many contexts.
The final can be:
1. variable
2. method
3. class
➢ The final keyword can be applied to the variables, a final variable that has no
value is called blank final variable or uninitialized final variable.
➢ It can be initialized in the constructor only.
➢ The blank final variable can be static also which will be initialized in the static
block only.
1) Java final variable:
➢ If you make any variable final, you cannot change the value of final variable
(It will be constant).
Example:
➢ There is a final variable speed limit, we are going to change the value of this
variable, but It can't be changed because final variable once assigned a value
can never be changed.
class Bike9
{
final int speedlimit=90; //final variable
void run()
{
speedlimit=400;
}
public static void main(String args[])
{
Bike9 obj=new Bike9();
obj.run();
} } //end of class
Output:
Example:
class Bike
{
final void run()
{
System.out.println("running");
} }
class Honda extends Bike
{
void run(){System.out.println("running safely with 100kmph");
}
public static void main(String args[])
{
Honda honda= new Honda();
honda.run();
} }
Output:
Example:
final class Bike
{
}
class Honda1 extends Bike
{
void run(){System.out.println("running safely with 100kmph");
}
public static void main(String args[])
{
Honda1 honda= new Honda1();
honda.run();
} }
Output:
Example:
class Bike
{
final void run(){System.out.println("running...");
}
}
class Honda2 extends Bike
{
public static void main(String args[])
{
new Honda2().run();
} }
What is a blank or uninitialized final variable?
Example:
class Student
{
int id;
String name;
final String PAN_CARD_NUMBER;
...
}
Output: 70
static blank final variable
➢ A static final variable that is not initialized at the time of declaration is known
as static blank final variable. It can be initialized only in static block.
Example:
class A
{
static final int data;//static blank final variable
static
{
data=50;
}
public static void main(String args[])
{
System.out.println(A.data);
} }
Example:
class Bike11
{
int cube(final int n)
{
n=n+2;//can't be changed as n is final
n*n*n;
}
public static void main(String args[])
{
Bike11 b=new Bike11();
b.cube(5);
} }
Output:
➢ If subclass (child class) has the same method as declared in the parent
class, it is known as method overriding in Java.
➢ In other words, If a subclass provides the specific implementation of the
method that has been declared by one of its parent class, it is known as
method overriding.
1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).
Understanding the problem without method overriding:
➢ Let's understand the problem that we may face in the program if we don't
use method overriding.
Example:
//Java Program to demonstrate why we need method overriding
//Here, we are calling the method of parent class with child
//class object.
//Creating a parent class
class Vehicle
{
void run(){System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike extends Vehicle
{
public static void main(String args[])
{
//creating an instance of child class
Bike obj = new Bike();
//calling the method with child class instance
obj.run();
} }
Output:
Vehicle is running
Problem is that I have to provide a specific implementation of run() method
in subclass that is why we use method overriding.
➢ In this example, we have defined the run method in the subclass as defined in the
parent class but it has some specific implementation. The name and parameter
of the method are the same, and there is IS-A relationship between the classes,
so there is method overriding.
Example:
//Java Program to illustrate the use of Java Method Overriding
//Creating a parent class.
class Vehicle
{
//defining a method
void run(){System.out.println("Vehicle is running");
} }
//Creating a child class
class Bike2 extends Vehicle
{
//defining the same method as in the parent class
void run(){System.out.println("Bike is running safely");
}
Output:
Output:
In case of method
In case of method overriding, parameter
3) overloading, parameter must be
must be same.
different.
Type Description
Member Inner Class A class created within class and outside method.
Static Nested Class A static class was created within the class.
Keyword Description
➢ Java defines several types of exceptions that relate to its various class
libraries. Java also allows users to define their own exceptions.
try-catch Syntax:
try
{
// Code that may throw an exception
} catch (ExceptionType e)
{
// Code to handle the exception
}
throw Syntax:
throw me;
➢ In main() method, the details are displayed using a for-loop.
➢ At this time, a check is done if in any account the balance amount is less
than the minimum balance amount in the account.
➢ If it is so, then MyException is raised and a message is displayed “Balance
amount is less”.
Example:
// default constructor
MyException() { }
// parameterized constructor
MyException(String str) { super(str); }
// write main()
public static void main(String[] args)
{
try {
// display the heading for the table
System.out.println("ACCNO" + "\t" + "CUSTOMER" + "\t" +
"BALANCE");
// display the actual account information
for (int i = 0; i < 5 ; i++)
{
System.out.println(accno[i] + "\t" + name[i] + "\t" + bal[i]);
// display own exception if balance < 1000
if (bal[i] < 1000)
{
MyException me =
new MyException("Balance is less than 1000");
throw me;
} } } //end of try
catch (MyException e)
{
e.printStackTrace();
} } }
Runtime Error:
MyException: Balance is less than 1000
at MyException.main(fileProperty.java:36)
Output:
ACCNO CUSTOMER BALANCE
1001 Nish 10000.0
1002 Shubh 12000.0
1003 Sush 5600.0
1004 Abhi 999.0
try {
checkAge(20); // This will not throw an exception
} catch (AgeNotValidException e) {
System.out.println("Caught an exception: " + e.getMessage());
}
}
}
Example Using All Keywords:
import java.io.*;
public class ExceptionHandlingExample
{
// Method that declares it throws an exception
public static void readFile() throws IOException
{
FileReader file = new FileReader("test.txt");
BufferedReader fileInput = new BufferedReader(file);
static <T extends Object & It is used to get the maximum value
31) Comparable<? super T>> max() of the given collection, according to
T the natural ordering of its elements.
static <T extends Object & It is used to get the minimum value
32) Comparable<? super T>> min() of the given collection, according to
T the natural ordering of its elements.
import java.util.*;
public class CollectionsExample
{
public static void main(String a[])
{
List<String> list = new ArrayList<String>();
list.add("C");
list.add("Core Java");
list.add("Advance Java");
System.out.println("Initial collection value:"+list);
Collections.addAll(list, "Servlet","JSP");
System.out.println("After adding elements collection value:"+list);
String[] strArr = {"C#", ".Net"};
Collections.addAll(list, strArr);
System.out.println("After adding array collection value:"+list);
}
}
Output:
import java.util.*;
public class CollectionsExample
{
public static void main(String a[])
{
List<Integer> list = new ArrayList<Integer>();
list.add(46);
list.add(67);
list.add(24);
list.add(16);
list.add(8);
list.add(12);
System.out.println("Value of maximum element from the collection:
"+Collections.max(list));
}
}
Output:
What is Collection:
➢ A Collection represents a single unit of objects, i.e., a group.
What is a framework:
➢ It provides readymade architecture.
➢ It represents a set of classes and interfaces.
➢ It is optional.
➢ There are various methods in List interface that can be used to insert,
delete, and access the elements from the list.
i). ArrayList:
import java.util.*;
class TestJavaCollection1
{
public static void main(String args[])
{
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Ravi");//Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
//Traversing list through Iterator
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
} } }
Output:
Ravi
Vijay
Ravi
Ajay
ii) LinkedList:
Ravi
Vijay
Ravi
Ajay
iii). Vector:
import java.util.*;
public class TestJavaCollection3
{
public static void main(String args[])
{
Vector<String> v=new Vector<String>();
v.add("Ayush");
v.add("Amit");
v.add("Ashish");
v.add("Garima");
Iterator<String> itr=v.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
} } }
Output:
Ayush
Amit
Ashish
Garima
iv). Stack:
Ayush
Garvit
Amit
Ashish
(2). Queue Interface:
import java.util.*;
public class TestJavaCollection5
{
public static void main(String args[])
{
PriorityQueue<String> queue=new PriorityQueue<String>();
queue.add("Amit Sharma");
queue.add("Vijay Raj");
queue.add("JaiShankar");
queue.add("Raj");
System.out.println("head:"+queue.element());
System.out.println("head:"+queue.peek());
System.out.println("iterating the queue elements:");
Iterator itr=queue.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
queue.remove();
queue.poll();
System.out.println("after removing two elements:");
Iterator<String> itr2=queue.iterator();
while(itr2.hasNext())
{
System.out.println(itr2.next());
} } }
Output:
head:Amit Sharma
head:Amit Sharma
iterating the queue elements:
Amit Sharma
Raj
JaiShankar
Vijay Raj
after removing two elements:
Raj
Vijay Raj
(3). Deque Interface:
(i). ArrayDeque:
Gautam
Karan
Ajay
mport java.util.*;
public class TestJavaCollection7
{
public static void main(String args[])
{
//Creating HashSet and adding elements
HashSet<String> set=new HashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//Traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
} } }
Output:
Vijay
Ravi
Ajay
(ii). LinkedHashSet:
Ravi
Vijay
Ajay
(5). SortedSet Interface:
(i). TreeSet:
➢ Java TreeSet class implements the Set interface that uses a tree for
storage.
➢ Like HashSet, TreeSet also contains unique elements.
➢ However, the access and retrieval time of TreeSet is quite fast. The
elements in TreeSet stored in ascending order.
import java.util.*;
public class TestJavaCollection9
{
public static void main(String args[])
{
//Creating and adding elements
TreeSet<String> set=new TreeSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
} } }
Output:
Ajay
Ravi
Vijay
For example:
Map<T> hm = new HashMap<> ();
Map<T> tm = new TreeMap<> ();
Output:
➢ There are various methods in List interface that can be used to insert,
delete, and access the elements from the list.
i). ArrayList:
import java.util.*;
class TestJavaCollection1
{
public static void main(String args[])
{
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Ravi");//Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
//Traversing list through Iterator
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
} } }
Output:
Ravi
Vijay
Ravi
Ajay
ii) LinkedList:
Ravi
Vijay
Ravi
Ajay
iii). Vector:
import java.util.*;
public class TestJavaCollection3
{
public static void main(String args[])
{
Vector<String> v=new Vector<String>();
v.add("Ayush");
v.add("Amit");
v.add("Ashish");
v.add("Garima");
Iterator<String> itr=v.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
} } }
Output:
Ayush
Amit
Ashish
Garima
iv). Stack:
Ayush
Garvit
Amit
Ashish
(2). Queue Interface:
import java.util.*;
public class TestJavaCollection5
{
public static void main(String args[])
{
PriorityQueue<String> queue=new PriorityQueue<String>();
queue.add("Amit Sharma");
queue.add("Vijay Raj");
queue.add("JaiShankar");
queue.add("Raj");
System.out.println("head:"+queue.element());
System.out.println("head:"+queue.peek());
System.out.println("iterating the queue elements:");
Iterator itr=queue.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
queue.remove();
queue.poll();
System.out.println("after removing two elements:");
Iterator<String> itr2=queue.iterator();
while(itr2.hasNext())
{
System.out.println(itr2.next());
} } }
Output:
head:Amit Sharma
head:Amit Sharma
iterating the queue elements:
Amit Sharma
Raj
JaiShankar
Vijay Raj
after removing two elements:
Raj
Vijay Raj
(i). ArrayDeque:
Output:
Gautam
Karan
Ajay
mport java.util.*;
public class TestJavaCollection7
{
public static void main(String args[])
{
//Creating HashSet and adding elements
HashSet<String> set=new HashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//Traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
} } }
Output:
Vijay
Ravi
Ajay
(ii). LinkedHashSet:
Ravi
Vijay
Ajay
(5). SortedSet Interface:
(i). TreeSet:
➢ Java TreeSet class implements the Set interface that uses a tree for
storage.
➢ Like HashSet, TreeSet also contains unique elements.
➢ However, the access and retrieval time of TreeSet is quite fast. The
elements in TreeSet stored in ascending order.
import java.util.*;
public class TestJavaCollection9
{
public static void main(String args[])
{
//Creating and adding elements
TreeSet<String> set=new TreeSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
} } }
Output:
Ajay
Ravi
Vijay
For example:
Map<T> hm = new HashMap<> ();
Map<T> tm = new TreeMap<> ();
Output:
Java I/O:
➢ Java I/O (Input and Output) is used to process the input and produce the
output.
➢ Java uses the concept of a stream to make I/O operation fast.
➢ The java.io package contains all the classes required for input and
output operations.
Stream:
OutputStream vs InputStream:
OutputStream
➢ Java application uses an output stream to write data to a destination; it
may be a file, an array, peripheral device or socket.
InputStream
➢ Java application uses an input stream to read data from a source; it may
be a file, an array, peripheral device or socket.
Let's understand the working of Java OutputStream and InputStream by the
figure given below.
OutputStream class:
InputStream class:
➢ InputStream class is an abstract class. It is the superclass of all classes
representing an input stream of bytes.
Method Description
3) public void close()throws IOException is used to close the current input stream.
InputStream Hierarchy:
Character Streams:
➢ The java.io package provides CharacterStream classes to overcome
the limitations of ByteStream classes, which can only handle the 8-bit
bytes and is not compatible to work directly with the Unicode characters.
➢ CharacterStream classes are used to work with 16-bit Unicode
characters.
➢ They can perform operations on characters, char arrays and
Strings.
➢ However, the CharacterStream classes are mainly used to read
characters from the source and write them to the destination.
➢ The CharacterStream classes are divided into two types of classes,
1. Reader class and 2. Writer class.
1. Reader Class:
➢ Reader class is used to read the 16-bit characters from the input
stream.
➢ However, it is an abstract class and can't be instantiated, but various
subclasses inherit the Reader class and override the methods of the
Reader class.
➢ All methods of the Reader class throw an IOException. The subclasses
of the Reader class are given in the following table.
SN Class Description
1. BufferedReader This class provides methods to read characters from the buffer.
3. FileReader This class provides methods to read characters from the file.
This class provides methods to read characters from the
4. FilterReader
underlying character input stream.
SN Method Description
This method is used to read the specified nChars from the buffer
int read(char buffer[],
3 at the specified location. It returns the total number of characters
int loc, int nChars)
successfully read.
This method is used to reset the input pointer to the previous set
5 void reset()
mark.
long skip(long This method is used to skip the specified nChars characters from
6
nChars) the input stream and returns the number of characters skipped.
2. Writer Class:
➢ Writer class is used to write 16-bit Unicode characters to the output
stream. The methods of the Writer class generate IOException.
➢ Like Reader class, Writer class is also an abstract class that cannot be
instantiated; therefore, the subclasses of the Writer class are used to
write the characters onto the output stream.
➢ The subclasses of the Writer class are given in the below table.
SN Class Description
6 StringWriter This class provides methods to write the characters to the string.
➢ To write the characters to the output stream, the Write class provides
various methods given in the following table.
SN Method Description
void write(char buffer [],int This method is used to write the nChars characters
4
loc, int nChars) to the character array from the specified location.
Byte Streams:
➢ ByteStream classes are used to read bytes from the input stream
and write bytes to the output stream.
➢ In other words, we can say that ByteStream classes read/write the
data of 8-bits.
➢ We can store video, audio, characters, etc., by using ByteStream
classes. These classes are part of the java.io package.
➢ The ByteStream classes are divided into two types of classes,
1. InputStream and 2. OutputStream.
➢ These classes are abstract and super classes of all the Input/Output
stream classes.
1. InputStream Class:
➢ The InputStream class provides methods to read bytes from a file,
console or memory.
➢ It is an abstract class and can't be instantiated; however, various
classes inherit the InputStream class and override its methods.
➢ The subclasses of InputStream class are given in the following table.
SN Class Description
SN Method Description
SN Class Description
2 void write (byte buffer [] ) It is used to write a byte array to the output stream.
Void write(bytes buffer[],int It is used to write nByte bytes to the output stream
3
loc, int nBytes) from the buffer starting at the specified location.
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
Output:
A new file MyNewFile.doc will be created on desktop with the content "Learn new
technologies".
Threads - Thread states -Thread priority
Threads in Java:
Definition:
A thread is a lightweight process or the smallest unit of
processing in Java. Java allows for multi-threaded programming,
meaning multiple tasks can be performed simultaneously to
optimize performance.
Creation: There are two primary ways to create a thread in Java:
1. Extending the Thread class:
➢ A class can extend Thread and override the run() method.
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running..."); } }
public class Test {
public static void main(String[] args) {
MyThread t = new MyThread();
t.start(); // Start the thread
} }
2. Implementing the Runnable interface:
➢ A class implements Runnable and the run() method.
➢ Thread operations refer to the set of methods and actions you can
perform on Java threads.
➢ These operations allow thread management, coordination, and
communication between threads during execution.
➢ Common Thread Operations:
1. start(): Initiates a thread and calls its run() method.
Thread t = new Thread();
t.start(); // Starts the thread
2. run(): The main logic of the thread is placed here. This method is called
automatically when a thread is started, but it can also be called directly
(though it won’t start the thread separately).
try {
Thread.sleep(1000); // Pauses for 1 second
}
catch (InterruptedException e)
{
e.printStackTrace();
}
4. join(): Causes the current thread to wait for the completion of another
thread. This is used when you want to ensure a thread finishes before
proceeding further.
class Counter {
private int count = 0;
MyThread(Counter counter) {
this.counter = counter;
}
Multithreading in Java:
➢ Multithreading is a process of executing multiple threads
simultaneously within a program. In Java, multithreading is a key
feature that allows the efficient use of CPU by sharing its time between
different threads (also known as time-slicing or concurrency).
Key Concepts in Multithreading:
Benefits of Multithreading:
➢ Improved Performance: Multithreading enhances the overall
performance of a program by allowing multiple tasks to run
concurrently.
➢ Resource Sharing: Threads share the same memory and
resources, making it efficient to work with shared data.
➢ Responsiveness: Multithreading helps to create responsive
applications. For example, a thread can handle background tasks
while another thread handles user input.
Example of Creating Multiple Threads:
class MyThread extends Thread {
public void run() {
System.out.println(Thread.currentThread().getName() + " is running...");
} }
public class Test
{
public static void main(String[] args)
{
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
t1.start(); // Start the first thread
t2.start(); // Start the second thread
} }
Here, two threads t1 and t2 run concurrently, and their outputs may
interleave.
Thread Lifecycle in Multithreading:
1. New: A thread is in this state when it is created but not yet started.
2. Runnable: The thread is ready to run and waiting for CPU time.
3. Running: The thread is actively running.
4. Blocked/Waiting: The thread is waiting for a resource or another
thread.
5. Terminated: The thread has finished executing.
Thread Example with sleep() and join():
class MyThread extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
try {
Thread.sleep(1000); // Sleep for 1 second
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(i + " - " + Thread.currentThread().getName());
} } }
public class Test
{
public static void main(String[] args) throws InterruptedException
{
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
t1.start(); // Start thread 1
t2.start(); // Start thread 2
t1.join(); // Main thread waits for t1 to finish
t2.join(); // Main thread waits for t2 to finish
System.out.println("Both threads have completed.");
} }
Explanation:
➢ sleep(1000) makes each thread sleep for 1 second between prints.
➢ join() ensures that the main thread waits for both t1 and t2 to finish
before proceeding.
Thread Synchronization Example:
class Table {
synchronized void printTable(int n) { // Synchronized method
for (int i = 1; i <= 5; i++) {
System.out.println(n * i);
try {
Thread.sleep(400);
} catch (Exception e) {
System.out.println(e);
} }} }
class MyThread1 extends Thread {
Table t;
MyThread1(Table t) {
this.t = t;
}
public void run() {
t.printTable(5); // Print table of 5
} }
class MyThread2 extends Thread {
Table t;
MyThread2(Table t) {
this.t = t;
}
public void run() {
t.printTable(100); // Print table of 100
} }
public class Test {
public static void main(String args[]) {
Table obj = new Table(); // Only one object
MyThread1 t1 = new MyThread1(obj);
MyThread2 t2 = new MyThread2(obj);
t1.start();
t2.start();
} }
Explanation:
➢ The printTable() method is synchronized, so when one thread
accesses it, the other must wait until the first thread finishes,
preventing interleaving.
Note:
Generic Collections:
Generic Classes:
Syntax:
class ClassName<T>
{
private T value;
ClassName(T value)
{
this.value = value;
}
T getValue()
{
return value;
} }
Example:
public T getData()
{
return data;
}
Generic Methods:
Syntax:
public <T> void methodName(T param)
{
// Method body
}
Example:
public class GenericMethodDemo
{
public static <T> void printArray(T[ ] array)
{
for (T element : array)
{
System.out.print(element + " ");
}
System.out.println();
}
Bounded Types:
Syntax:
class ClassName<T extends SuperClass>
{
// T must be SuperClass or its subclass
}
Example:
class Stats<T extends Number>
{
T[ ] nums;
Stats(T[] nums) {
this.nums = nums;
}
double average() {
double sum = 0.0;
for (T num : nums) {
sum += num.doubleValue();
}
return sum / nums.length;
}
}
public class BoundedTypeDemo {
public static void main(String[] args) {
Integer[] inums = {1, 2, 3, 4, 5};
Stats<Integer> iStats = new Stats<>(inums);
System.out.println("Average of integers: " + iStats.average());
Double[] dnums = {1.1, 2.2, 3.3};
Stats<Double> dStats = new Stats<>(dnums);
System.out.println("Average of doubles: " + dStats.average());
} }
Wildcards in Generics:
➢ Definition: A placeholder for an unknown type.
Types of Wildcards:
1. Unbounded (?):
➢ Accepts any type.
Example: List<?>
Multiple Bounds:
➢ Definition: A type parameter can extend multiple classes/interfaces
using the & operator.
Syntax:
class ClassName<T extends Class & Interface>
{
// Body
}
Example:
interface Printable
{
void print();
}
class BaseClass {
void show() {
System.out.println("Base class method");
}
}
class MultiBound<T extends BaseClass & Printable> {
T obj;
MultiBound(T obj) {
this.obj = obj;
}
void display() {
obj.show();
obj.print();
}
}
class DerivedClass extends BaseClass implements Printable {
public void print() {
System.out.println("Printable method");
}
}
public class MultiBoundsDemo {
public static void main(String[] args) {
DerivedClass obj = new DerivedClass();
MultiBound<DerivedClass> mb = new MultiBound<>(obj);
mb.display();
}
}
Output:
Base class method
Printable method
Advantages of Generics:
➢ Type Safety: Eliminates runtime type mismatch errors.
➢ Eliminates Casting: No need for explicit type casts.
➢ Code Reusability: Single codebase works with multiple data types.
➢ Improved Performance: Reduces the overhead of type checking and
casting.