Complete Core Java Book
Complete Core Java Book
Core Java
(Simplified Text Book)
SRINIVAS GARAPATI
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, AMEERPET, HYDERABAD
Contact for Online Classes: +91 – 911 955 6789 / 7306021113
Practice @ www.onlinejavacompiler.com
Contents
Core Java
Introduction:
Java developed by James Gosling.
Using Java, we can develop Desktop applications and Web applications.
Using Core concepts of Java,
o We develop Desktop applications.
Using Java technologies (Servlets, JDBC and JSP)
o We develop Web based applications.
Using Frameworks (Spring, Hibernate, SpringBoot etc)
o We achieve Rapid applications development.
Java distributions:
JSE(Java Standard Edition): contains the core concepts of Java by which we can
develop Desktop applications.
JEE(Java Enterprise Edition): contains advanced concepts of Java to develop Server
side applications.
JME(Java Micro Edition): concepts used to develop mobile applications, embedded
systems etc.
Multithreading:
Java supports multithreading.
Multithreading is a Java feature that allows concurrent execution of two or more parts of
a program for maximum utilization of CPU.
Java - Installation
Installing JDK:
We can download the latest version from official website:
https://www.oracle.com/java/technologies/downloads/
Download based on your Operating System.
For windows, download executable(.exe) file
Code.java:
public class Code
{
public static void main(String[] args)
{
System.out.println("Hello World!");
}
}
Naming conventions:
It is recommended to follow Java Naming rules while naming classes, methods, variables,
interfaces, constants etc.
Java Source code become more readable and understandable with naming rules.
Class: Every word in identity starts with capital letter. Spaces not allowed
String
PrintStream
NullPointerException
FileNotFoundException
ArrayIndexOutOfBoundsException
Method: First word starts with Lower Case and From Second word, every word starts with
capital letters. No spaces allowed.
main( )
getName( )
getAccountHolderNumber( )
Variable: First word starts with Lower Case and From Second word, every word starts with
capital letters. No spaces allowed
int sum = 0 ;
float shoeSize = 8.9 ;
Constant variable : All letters should be in upper case, words separate with underscore(_)
MIN_VALUE = 0;
MAX_PRIORITY = 10;
Variables
Variable: Identity given to memory location.
or
Named memory location
Syntax:
datatype identity = value;
Examples:
String name = “Amar”;
int age = 23;
char gender = ‘M’;
boolean married = false;
double salary = 35000.00;
Identifier rules:
Identifier is a name given to class, method, variable etc.
Identifier must be unique
Identifier is used to access the member.
Java - Datatypes
Data type:
In the declaration of every variable, it is mandatory to specify its data type.
Data type describes,
1. The size of memory allocated to variable.
2. The type of data allowed to store into variable.
Limits:
A data type limit describes the minimum and maximum values we can store into a
variable.
Every data type is having size and it is represented by bytes
One byte equals to 8 bits.
Integer types: We have 4 integer types among eight available primitive types in java.
Type Size(bytes) Limits
byte 1 -128(-2^7) to +127(2^7-1)
short 2 -32,768(-2^15) to 32,767(2^15-1)
int 4 -2,147,483,648(-2^31) to 2,147,483,647(2^31-1)
long 8 -9,223,372,036,854,775,808(-2^63) to
9,223,372,036,854,775,807(2^63-1)
Note:
For every primitive type, there is a corresponding wrapper class.
Wrapper classes providing pre-defined variables to find Size and Limits.
Character data type: Character type variable is used to store alphabets, digits and symbols.
class Code{
public static void main(String[] args) {
char x = 'A';
char y = '5';
char z = '$';
System.out.println("x val : " + x + "\ny val : " + y + "\nz val : " + z);
}
}
Type casting:
Conversion of data from one data type to another data type.
Type casting classified into
o Implicit cast: Auto conversion of data from one type to another type.
o Explicit cast: Manual conversion of data from one type to another type.
Convert Character to Integer: this conversion happens implicitly when we assign character to
integer type.
class Code
{
public static void main(String[] args) {
char ch = 'A' ;
int x = ch ;
System.out.println("x value : " + x);
}
}
class Code {
public static void main(String[] args) {
char up = 'A';
char lw = (char)(up+32);
System.out.println("Result : " + lw);
}
}
Convert Digit to Number: We can convert character type digit into number as follows
class Code {
public static void main(String[] args) {
char d = '5';
int n = d-48;
System.out.println("Result : " + n);
}
}
Note: Type casting not required in above code as we are assigning value to integer variable.
Decimal Numbers:
We store decimal values using 2 types float and double.
Formatting Output
Introduction: It is important to format the output before display the results to end user.
Proper formatting makes the user more understandable about program results.
We always display results in String format. To format the output, we concatenate the
values such as int, char, double, boolean with messages (string type) as follows:
Syntax Example
int + int = int 10 + 20 = 30
String + String = String “Java” + “Book” = JavaBook
“10” + “20” = 1020
String + int = String “Book” + 1 = Book1
“123” + 456 = 123456
String + int + int = String “Sum = “ + 10 + 20 = Sum1020
String + (int + int) = String “Sum = “ + (10 + 20) = Sum30
String + double = String “Value = “ + 23.45 = Value = 23.45
String – int = Error
Scanner Class:
Using java library class Scanner, we can read input like integers, characters, strings,
double values from the user.
Different methods to read different values such as nextInt(), next(), nextDouble()…
We need to specify the Keyboard(System.in) while creating Scanner class object.
o Scanner scan = new Scanner(System.in);
We access all the methods using object reference name.
Reading integer value: nextInt() method read and returns an integer value
import java.util.Scanner;
class ReadInt
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter integer : ");
int n = scan.nextInt();
System.out.println("n value is : " + n);
}
}
Reading Boolean value: nextBoolean() method returns Boolean value that we entered
import java.util.Scanner;
class ReadBoolean
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter boolean value : ");
boolean b = scan.nextBoolean();
System.out.println("b value is : " + b);
}
}
Reading String: using next() method we can read single word string from the user
import java.util.Scanner;
class Code
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter your name : ");
String name = scan.next();
System.out.println("Hello : " + name);
}
}
Reading character: There is no method in Scanner class to read single character, hence we read
first character of String to read single character as follows
import java.util.Scanner;
class Code {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter character : ");
char ch = scan.next().charAt(0);
System.out.println("Input character is : " + ch);
}
}
Reading multi-word String: nextLine() method can read string includes spaces
import java.util.Scanner;
class Code
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter string with spaces : ");
String s = scan.nextLine();
System.out.println("Input String is : " + s);
}
}
Java - Operators
Operator: Operator is a symbol that performs operation on operands.
Arithmetic operators:
These operators perform all arithmetic operations.
Operators are +, -, *, / , %
Division(/) : returns quotient after division
Mod(%) : returns remainder after division
Operators Priority: We need to consider the priority of operators if the expression has more
than one operator. Arithmetic operators follow BODMAS rule.
Priority Operator
() First. If nested then inner most is first
*, / and % Next to (). If several, from left to right
+, - Next to *, / , %. If several, from left to right
Relational operators: These operator return boolean value by validating the relation on data.
Operators are >, < , >=, <=, ==, !=
class Code {
public static void main(String[] args) {
int a=5, b=3 ;
System.out.println(a + ">" + b + "=" + (a>b));
System.out.println(a + "<" + b + "=" + (a<b));
System.out.println(a + "==" + b + "=" + (a==b));
System.out.println(a + "!=" + b + "=" + (a!=b));
}
}
Conditional Operator:
It is widely used to execute condition in true part or in false part.
It is a simplified form of if-else control statement.
Modify operators:
These are also called Increment and Decrement operators.
Modify operators are increase and decrease the value of variable by 1.
Operators are ++, -- ;
Logical Operators
A logical operator is primarily used to evaluate multiple expressions.
Logical operators return boolean value.
Operators are && , || and !
class Logical {
public static void main(String[] args) {
System.out.println("true && true : " + (true && true));
System.out.println("true && false : " + (true && false));
System.out.println("true || false : " + (true || false));
System.out.println("false || false : " + (false || false));
}
}
class Logical {
public static void main(String[] args) {
System.out.println("!true : " + (!true));
System.out.println("!false : " + (!false));
}
}
Bitwise Operators:
These operators are used to process the data at bit level.
These can be applied only integers and characters.
Operators are &, |, ^.
These operators process the data according to truth table.
class Bitwise{
public static void main(String[] args) {
int a=10, b=8 , c, d, e;
c = a&b ;
d = a|b ;
e = a^b ;
System.out.println(c+","+d+","+e);
}
}
Shift Operators:
The bitwise shift operators move the bit values of a binary object.
The left operand specifies the value to be shifted.
The right operand specifies the number of positions that the bits in the value are to be
shifted.
The bit shift operators take two arguments, and looks like:
x << n
x >> n
class Shift{
public static void main(String[] args) {
int a=8, b, c;
b = a>>2 ;
c = a<<2 ;
System.out.println(a+","+b+","+c);
}
}
Condition:
a >= 0
Condition:
a == 0
Condition:
a ==b
Condition:
a>b
Condition:
a*a == b
Condition:
a+b == 10 ;
Condition:
n % 3 == 0
Condition:
n % 2 == 0
Condition:
n % 10 == 0
Condition to check the multiplication of 2 numbers not equals to 3rd number or not:
Variables:
int a=?, b=?, c=?;
Condition:
a * b != c
Condition:
(m1 + m2+ m3+ m4)/4 >= 60
Condition to check the sum of First 2 numbers equals to last digit of 3rd num or not:
Variables:
int a=?, b=? , c=? ;
Condition:
a + b == c% 10
Condition:
quantity%12 == 0
Condition:
age >= 18
Condition to check First Num is greater than both Second & Third Nums or Not:
Variables:
int a=?, b=?, c=?;
Condition:
a > b && a > c
Condition:
n % 3 == 0 && n % 5 == 0
Condition:
n >= 30 && n <= 50
Condition:
m1>=35 && m2>=35 && m3>=35 && m4>=35 && m5>=35
Condition:
ch == ‘a’ || ch == ‘e’ || ch== ‘i’ || ch==’o’ || ch==’u’
Condition:
ch >= ‘A’ && ch <= ‘Z’
Condition:
(ch >= ‘A’ && ch <= ‘Z’) || (ch >= ‘a’ && ch <= ‘z’)
Condition:
a == b && b == c
Condition:
a==b || b==c || c=a
Condition:
a!=b && b!=c && c!=a
Control Statements
Sequential statements:
Statement is a line of code.
Sequential Statements execute one by one from top-down approach.
if(condition)
{
Logic;
}
if - else block: Else block can be used to execute an optional logic if the given condition has
failed.
Syntax Flow Chart
if (condition){
If – Stats;
}
else{
Else – Stats;
}
If-else-if ladder:
It is allowed to defined multiple if blocks sequentially.
It executes only one block among the multiple blocks defined.
Syntax Flow Chart
if(condition1){
Statement1;
}
else if(condition2){
Statement2;
}
else if(condition3){
Statement3;
}
else{
Statement4;
}
import java.util.Scanner;
class Code
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter year : ");
int n = scan.nextInt();
if((n%400==0))
System.out.println("Leap year");
else if(n%4==0 && n%100!=0)
System.out.println("Leap Year");
else
System.out.println("Not leap year");
}
}
Nested if block: Defining a block inside another block. Inner if block condition evaluates only if
the outer condition is valid. It is not recommended to write many levels to avoid complexity.
Syntax Flow Chart
if (condition){
if (condition){
If - If….
}
else {
If - Else….
}
}
else {
if (condition){
Else - If….
}
else {
Else - Else….
}
}
Give the student grade only if the student passed in all subjects:
class Code
{
public static void main(String[] args) {
int m1=45, m2=67, m3=44;
if(m1>=40 && m2>=40 && m3>=40){
int total = m1+m2+m3;
int avg = total/3;
if(avg>=60)
System.out.println("Grade-A");
else if(avg>=50)
System.out.println("Grade-B");
else
System.out.println("Grade-C");
}
else
{
System.out.println("Student failed");
}
}
}
Introduction to Loops
Note: Block executes only once whereas Loop executes until condition become False
For Loop: We use for loop only when we know the number of repetitions. For example,
Print 1 to 10 numbers
Print Array elements
Print Multiplication table
Print String character by character in reverse order
While loop: We use while loop when we don’t know the number of repetitions.
Display contents of File
Display records of Database table
Do while Loop: Execute a block at least once and repeat based on the condition.
ATM transaction: When we swipe the ATM card, it starts the first transaction. Once the
first transaction has been completed, it asks the customer to continue with another
transaction and quit.
For Loop
for loop: Execute a block of instructions repeatedly as long as the condition is valid. We
use for loop only when we know the number of iterations to do.
While Loop
While loop: Execute a block of instructions repeatedly until the condition is false. We
use while loop only when don’t know the number of iterations to do.
while(condition)
{
statements;
}
int n = scan.nextInt();
int sum=0;
while(n!=0)
{
sum = sum + n%10;
n=n/10;
}
System.out.println("Sum of digits : " + sum);
}
}
break: A branching statement that terminates the execution flow of a Loop or Switch
case.
class Code {
public static void main(String[] args) {
for (int i=1 ; i<=10 ; i++){
if(i==5){
break;
}
System.out.print(i + " ");
}
}
}
Output: 1 2 3 4
Continue: A branching statement that terminates the current iteration of loop execution.
class Code {
public static void main(String[] args) {
for (int i=1 ; i<=10 ; i++){
if(i==5){
continue;
}
System.out.print(i + " ");
}
}
}
Output: 1 2 3 4 5 6 7 8 9 10
Switch case
Switch: It is a conditional statement that executes specific set of statements(case) based on
given choice. Default case executes if the user entered invalid choice. Case should terminate
with break statement.
Syntax FlowChart
switch(choice)
{
case 1 : Statements ;
break
case 2 : Statements ;
break
......
case n : Statements ;
break
default: Statements ;
}
import java.util.Scanner;
class Code {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter character(r, g, b) : ");
char ch = sc.next().charAt(0);
switch(ch){
case 'r' : System.out.println("Red");
break;
case 'g' : System.out.println("Green");
break;
case 'b' : System.out.println("Blue");
break;
default : System.out.println("Weird");
}
}
}
Output: Enter character(r, g, b): g
Green
Do-While Loop
do-while: Executes a block at least once and continue iteration until condition is false.
do
{
statements;
} while(condition);
Introduction to OOPS
Application:
Programming Languages and Technologies are used to develop applications.
Application is a collection of Programs.
We need to design and understand a single program before developing an application.
1. Identity:
o Identity of a program is unique.
o Programs, Classes, Variables and Methods having identities
o Identities are used to access these members.
2. Variable:
o Variable is an identity given to memory location.
or
o Named Memory Location
o Variables are used to store information of program(class/object)
Syntax Examples
3. Method:
Method is a block of instructions with an identity
Method performs operations on data(variables)
Method takes input data, perform operations on data and returns results.
Syntax Example
returntype identity(arguments) int add(int a, int b)
{ {
body; int c = a+b;
} return c;
}
Class: Class contains variables and methods. Java application is a collection of classes
Syntax Example
class Account{
long num;
class ClassName String name;
{ double balance;
Variables ; void withdraw(){
& logic;
Methods ; }
} void deposit(){
logic;
}
}
Object: Object is an instance of class. Instance (non static) variables of class get memory inside
the Object.
Syntax:
ClassName reference = new ClassName();
Example:
Account acc = new Account();
Note: Class is a Model from which we can define multiple objects of same type
Encapsulation:
The concept of protecting the data with in the class itself.
Implementation rules: (POJO rules)
o Class is Public (to make visible to other classes).
o Variables are Private (other objects cannot access the data directly).
o Methods are public (to send and receive the data).
Inheritance:
Defining a new class by re-using the members of other class.
We can implement inheritance using “extends” keyword.
Terminology:
o Parent/Super class: The class from which members are re-used.
o Child/Sub class: The class which is using the members
Abstraction:
Abstraction is a concept of hiding implementations and shows functionality.
Abstraction describes "What an object can do instead how it does it?".
Polymorphism:
Polymorphism is the concept where object behaves differently in different situations.
Types of Relations between Classes/Objects in Java: There are three most common
relationships among classes in Java that are as follows:
Use-A relation: When we create an object of a class inside a method of another class, this
relationship is called dependence relationship in Java, or simply Uses-A relationship.
Has-A relation: When an object of one class is created as data member inside another class, it
is called association relationship in java or simply Has-A relationship.
Is-A relation: Is-A relationship defines the relationship between two classes in which one class
extends another class.
Class Members
Class Members:
The Members which we can define inside the class.
Class Members includes
o Variables
o Methods
o Blocks
o Constructor
1. Static Variables: Store common information of all Objects. Access static variables using
class-name.
2. Instance Variables: Store specific information of Object. Access instance variables using
object-reference.
3. Method Parameters: Takes input in a Method. Access Method parameters directly and
only inside the method.
4. Local Variables: Store processed information inside the Method. Access local variables
directly and only inside the method.
Blocks:
Block is a set of instructions without identity
Block is either static or instance(anonymous)
Static Block: Defining a block using static-keyword. JVM invokes static block when class
execution starts.
static
{
statements;
}
Instance Block: Defining a block without static-keyword. JVM invokes instance block every time
when object creates.
{
statements;
}
Methods:
A Block of instructions with an identity.
Method takes input, process input and returns output
Methods performs operations on data
Static Method: Defining a method using static keyword. We can access static methods using
class-name.
static void display(){
logic;
}
Instance Method: Defining a method without static keyword. We can access instance methods
using object-reference.
void display(){
logic;
}
Constructor: Defining a method with class name. Return type is not allowed. We must invoke
the constructor in object creation process.
class Account{
Account(){
statements;
}
}
Static Members:
Defining class member with static keyword.
Static members are:
o Static main() method
o Static Block
o Static Method
o Static Variable
Class without main(): We can define class without main() method but we cannot run that class.
Runtime Error: No main() method in class Code. Please define main() method
Static block:
Define a block with static-keyword.
JVM invokes when class execution starts.
Static block executes before main() method.
class Pro {
static{
System.out.println("Static block");
}
public static void main(String args[]){
System.out.println("Main method");
}
}
Output:
Static Block
Main method
Methods
Method:
A block of instructions having identity.
Methods takes input(parameters), process input and return output.
Methods are used to perform operations on data
Syntax Example
returntype identity(arguments){ int add(int a, int b){
statements; int c=a+b;
} return c;
}
Classification of Methods: Based on taking input and returning output, methods are classified
into 4 types.
Method Definition: Method definition consists logic to perform the task. It is a block.
Method Call: Method Call is used to invoke the method logic. It is a single statement.
Static Variables
Static Variable:
Defining a variable inside the class and outside to methods.
Static variable must define with static keyword.
Static Variable access using Class-Name.
class Bank
{
static String bankName = "AXIS";
}
Note: We always process the data (perform operations on variables) using methods.
class Code {
static int a;
static void setA(int a){
Code.a = a;
}
static int getA(){
return Code.a;
}
public static void main(String[] args){
Code.setA(10);
System.out.println("A val : " + Code.getA());
}
}
class Code
{
static int a;
static double b;
static char c;
static boolean d;
static String e;
static void values(){
System.out.println("Default values : ");
System.out.println("int : " + Code.a);
System.out.println("double : " + Code.b);
System.out.println("char : " + Code.c);
System.out.println("boolean : " + Code.d);
System.out.println("String : " + Code.e);
}
public static void main(String[] args){
Code.values();
}
}
It is recommended to define get() and set() method to each variable in the class:
class First{
static int a, b, c;
static void setA(int a){
First.a = a;
}
static void setB(int b){
First.b = b;
}
static void setC(int c){
First.c = c;
}
static int getA(){
return First.a;
}
static int getB(){
return First.b;
}
static int getC(){
return First.c;
}
}
class Second
{
public static void main(String[] args)
{
First.setA(10);
First.setB(20);
First.setC(30);
System.out.println("A val : " + First.getA());
System.out.println("B val : " + First.getB());
System.out.println("C val : " + First.getC());
}
}
Instance Members:
Instance members also called non-static members.
Instance members related to Object.
We invoke instance members using Object-address
Constructor:
Defining a method with Class-Name.
Constructor Not allowed return-type.
class Employee {
Employee(){
System.out.println("Constructor");
}
}
Instance Method:
Defining a method without static keyword.
We must invoke the method using object-reference.
Instance Variables:
Defining a variable inside the class and outside to methods.
Instance variables get memory inside every object and initializes with default values.
this:
It is a keyword and pre-defined instance variable in java.
It is also called Default Object Reference Variable.
“this-variable” holds object address.
o this = object_address;
It is used to access object inside the instance methods and constructor.
Parameterized constructor:
Constructor with parameters is called Parametrized constructor.
We invoke the constructor in every object creation process.
Parameterized constructor is used to set initial values to instance variables in Object
creation process.
Note: We invoke the constructor with parameter values in object creation as follows
class Test
{
int a;
Test(int a){
this.a = a;
}
public static void main(String[] args) {
Test obj = new Test(10); // pass value while invoking constructor
}
}
Access Modifiers
Access Modifiers:
Access modifiers are used to set permissions to access the Class and its members
(variables, methods & constructors).
Java supports 4 access modifiers
o private
o <package> or <default>
o protected
o public
Note: We cannot apply access modifiers to blocks(we cannot access because no identity)
public class Pro{
private int x;
private Pro(){
}
protected void fun(){
}
static{
// Error:
}
}
Understanding the Access Modifiers with simple diagram:
Encapsulation:
The concept of protecting the data with in the class itself.
We implement Encapsulation through POJO rules
POJO – Plain Old Java Object
AccessEmployee.java:
class AccessEmployee{
public static void main(String[] args) {
Employee e = new Employee();
e.setNum(101);
e.setName("Amar");
e.setSalary(35000);
System.out.println("Emp Num : "+e.getNum());
System.out.println("Emp Name : "+ e.getName());
System.out.println("Emp Salary : "+e.getSalary());
}
}
Constructor Chaining:
Invoking constructor from another constructor is called Chaining.
this() method is used to invoke constructor.
class Pro
{
Pro(){
System.out.println("Zero args constructor");
}
Pro(int x){
this();
System.out.println("Args constructor");
}
public static void main(String args[]){
new Pro(10);
}
}
In constructor chaining, one constructor can be connected to only one constructor, hence
call to this() must be the first statement in constructor.
Inheritance
Inheritance:
Defining a new class by re-using the members of other class.
We can implement inheritance using “extends” keyword.
Terminology:
o Parent/Super class: The class from which members are re-used.
o Child/Sub class: The class which is using the members
Types of Inheritance:
1. Single Inheritance
2. Multi-Level Inheritance
3. Hierarchical Inheritance
class A{
....
}
class B extends A{
....
}
class C extends B{
....
}
class A{
....
}
class B extends A{
....
}
class C extends A{
....
}
class A{
....
}
class B{
....
}
class C extends A, B{
....
}
Single Inheritance:
class Employee
{
void doWork()
{
System.out.println("Employee do work");
}
}
class Manager extends Employee
{
void monitorWork()
{
System.out.println("Manage do work as well as monitor others work");
}
}
class Company
{
public static void main(String[] args)
{
Manager m = new Manager();
m.doWork();
m.monitorWork();
}
}
In Object creation, Parent object creates first to inherit properties into Child.
We can check this creation process by defining constructors in Parent and Child.
class Parent{
Parent(){
System.out.println("Parent object created");
}
}
this this()
A reference variable used to invoke instance It is used to invoke the constructor of same
members. class.
It must be used inside instance method or It must be used inside the constructor.
instance block or constructor.
super super()
A reference variable used to invoke instance It is used to invoke the constructor of same
members of Parent class from Child class. class.
It must be used inside instance method or It must be used inside Child class constructor.
instance block or constructor of Child class.
super():
In inheritance, we always create Object to Child class.
In Child object creation process, we initialize instance variables of by invoking Parent
constructor from Child constructor using super().
class Parent
{
int a, b;
Parent(int a, int b)
{
this.a = a;
this.b = b;
}
}
Polymorphism:
Polymorphism is the concept where object behaves differently in different situations.
class Calculator
{
void add(int x, int y) {
int sum = x+y;
System.out.println("Sum of 2 numbers is : " + sum);
}
void add(int x, int y, int z) {
int sum = x+y+z;
System.out.println("Sum of 3 numbers is : " + sum);
}
}
class Main
{
public static void main(String[] args) {
Calculator calc = new Calculator();
calc.add(10, 20);
calc.add(10, 20, 30);
}
}
println() method is pre-defined and overloaded. Hence it can print any type of data:
class Overload {
public static void main(String[] args) {
System.out.println(10);
System.out.println(12.345);
System.out.println('g');
System.out.println("java");
}
}
class Pro {
public static void main(String[] args) {
System.out.println("Standard main invoked by JVM");
Pro obj = new Pro();
obj.main();
Pro.main(10);
}
void main(){
System.out.println("No args main");
}
static void main(int x){
System.out.println("One arg main");
}
}
public static final int a; static public final int a; final static public int a;
final public static int a; static final public int a; public final static int a;
Runtime polymorphism:
Runtime Polymorphism is a Method overriding technique.
Defining a method in the Child class with the same name and same signature of its
Parent class.
We can implement Method overriding only in Parent-Child (Is-A) relation.
Child object shows the functionality(behavior) of Parent and Child is called Polymorphism
class Parent{
void behave(){
System.out.println("Parent behavior");
}
}
class Child extends Parent{
void behave(){
System.out.println("Child behavior");
}
void behavior(){
super.behave();
this.behave();
}
}
class Main{
public static void main(String[] args){
Child child = new Child();
child.behavior();
}
}
Object Up-casting:
We can store the address of Child class into Parent type reference variable.
Using parent address reference variable, we can access the functionality of Child class.
class Parent {
void fun(){
System.out.println("Parent's functionality");
}
}
Down casting: The concept of collecting Child object address back to Child type reference
variable from Parent type.
final:
Final is a keyword/modifier.
A member become constant if we define it as final hence cannot be modified.
We can apply final to Class or Method or Variable.
Abstraction
Abstraction:
Abstraction is a concept of hiding implementations and shows required functionality.
Abstraction describes "What an object can do instead how it does it?".
Abstract Class:
Define a class with abstract keyword.
Abstract class consists concrete methods and abstract methods.
Note: We cannot instantiate (create object) to abstract class because it has undefined methods.
class Main
{
public static void main(String[] args){
Demo obj = new Demo(); // Error:
}
}
import java.util.Scanner ;
abstract class Parent
{
String pname;
Parent(String pname){
this.pname = pname ;
}
abstract void details();
}
class Child extends Parent
{
String cname ;
Child(String pname, String cname) {
super(pname);
this.cname = cname ;
}
void details(){
System.out.println("Parent Name is: "+super.pname);
System.out.println("Child Name is : "+this.cname);
}
}
class Main
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter Parent Name : ");
String pname = scan.next();
System.out.print("Enter Child Name : ");
String cname = scan.next();
Child obj = new Child(pname, cname);
obj.details();
}
}
Interfaces
Interface:
Interface allow to define only abstract methods.
Interface methods are ‘public abstract’ by default.
interface Sample {
void m1();
void m2();
}
implements:
‘implements’ is a keyword.
Interface must ‘implements’ by class.
Implemented class override all abstract methods of an interface.
interface First {
void m1();
void m2();
}
class Second implements First{
public void m1(){
System.out.println("m1....");
}
public void m2(){
System.out.println("m2....");
}
}
class Main {
public static void main(String[] args){
First obj = new Second();
obj.m1();
obj.m2();
}
}
Upcasting: object reference of implemented class storing into Interface type variable
Relations:
class A{
}
class B{
}
class C extends A, B {
}
Error:
class A{
}
interface B{
}
class C extends A implements B {
}
interface A{
}
interface B{
}
interface C extends A, B {
}
Objects - Relations
Use-A relation: When we create an object of a class inside a method of another class, this
relationship is called dependence relationship in Java, or simply Uses-A relationship.
Is-A relation: Is-A relationship defines the relationship between two classes in which one class
extends another class.
Has-A relation: When an object of one class is created as data member inside another class, it
is called association relationship in java or simply Has-A relationship.
Association:
Association is a relationship between two objects.
It’s denoted by “has-a” relationship.
In this relationship all objects have their own lifecycle and there is no owner.
In Association, both object can create and delete independently.
Many to One: One Menu Item can be ordered by any number of Customers
class Author
{
String authorName;
int age;
String place;
class Book
{
String name;
int price;
Author auther;
Book(String n, int p, Author auther)
{
this.name = n;
this.price = p;
this.auther = auther;
}
void bookDetails()
{
System.out.println("Book Name: " + this.name);
System.out.println("Book Price: " + this.price);
}
void authorDetails()
{
System.out.println("Auther Name: " + this.auther.authorName);
System.out.println("Auther Age: " + this.auther.age);
System.out.println("Auther place: " + this.auther.place);
}
public static void main(String[] args)
{
Author auther = new Author("Srinivas", 33, "INDIA");
Book obj = new Book("Java-OOPS", 200, auther);
obj.bookDetails();
obj.authorDetails();
}
}
import java.util.*;
abstract class Plan
{
abstract double getRate();
public void calculateBill(double rate, int units)
{
System.out.println(units*rate);
}
}
class DomesticPlan extends Plan{
public double getRate(){
return 3.50;
}
}
class CommercialPlan extends Plan{
public double getRate(){
return 7.50;
}
}
class InstitutionalPlan extends Plan{
public double getRate(){
return 5.50;
}
}
class GetPlan
{
public Plan getPlan(String plan){
if(plan == null){
return null;
}
if(plan.equals("domestic")) {
return new DomesticPlan();
}
else if(plan.equals("commercial")){
return new CommercialPlan();
}
else if(plan.equals("institutional")) {
return new InstitutionalPlan();
}
return null;
}
}
class GenerateBill
{
public static void main(String args[])
{
GetPlan plan = new GetPlan();
System.out.print("Enter plan name : ");
Plan p = plan.getPlan(name);
System.out.print("Bill for " + name + " plan of " + units + " units is : ");
double rate = p.getRate();
p.calculateBill(rate, units);
}
}
Singleton Pattern: Ensure that only one instance of the class exists.
Provide global access to that instance by:
1. Declaring all constructors of the class to be private.
2. Providing a static method that returns a reference to the instance. The lazy initialization
concept is used to write the static methods.
3. The instance is stored as a private static variable.
class Printer
{
private static Printer printer = new Printer();
private Printer()
{
// empty
}
public static Printer getPrinter()
{
return printer;
}
void takePrints()
{
System.out.println("Printing...");
}
}
class UsePrinter
{
public static void main(String[] args)
{
Printer printer = Printer.getPrinter();
printer.takePrints();
}
}
Note: We need to synchronize takePrints() method of Printer class when multiple threads
trying take prints parallel.
Arrays in Java
Array:
Array is a collection of similar data elements.
Arrays are objects in Java.
Arrays are static(fixed in size).
Syntax :
datatype identity[ ] = new datatype[size];
Example :
int arr[ ] = new int[5];
Declaration of array: The following code describes how to declare array variable in java. We
must allocate the memory to this variable before storing data elements.
class Code {
public static void main(String[] args) {
int arr[];
}
}
length: ‘length’ is an instance variable of Array class. It returns the length of array.
class Code {
public static void main(String[] args) {
int arr[ ] = new int[5];
int len = arr.length ;
System.out.println("Length is : " + len);
}
}
class Code {
public static void main(String[] args) {
int arr[ ] = {10,20,30,40,50};
System.out.println("Array elements are : ");
for (int i=0 ; i<arr.length ; i++){
System.out.println(arr[i]);
}
}
}
Program read the Size and elements of array – Print their Sum:
import java.util.Scanner ;
class Code {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int sum=0;
for (int i=0 ; i<n ; i++){
sum = sum + arr[i];
}
System.out.println("Sum of elements : " + sum);
}
}
Syntax :
for(<data_type> <var> : <array>or<collection>){
Processing logic…
}
Arrays Class
Arrays class:
Java library class belongs to java.util package.
Arrays class providing set of method to process array elements.
Some of the methods as follows.
static void sort(int[] a) Sorts the specified array into ascending numerical order.
static String toString(int[] a) Returns a string representation of the contents of the
specified array.
static <T> List<T> asList(T... a) Returns a fixed-size list backed by the specified array.
static int binarySearch(int[] a, int Searches the specified array of ints for the specified
key) value using the binary search algorithm
static int[] copyOfRange(int[] Copies the specified range of the specified array into a
original, int from, int to) new array.
static boolean equals(int[] a, int[] Returns true if the two specified arrays of ints are equal
a2) to one another.
static void fill(int[] a, int val) Assigns the specified int value to each element of the
specified array of ints.
Arrays.sort(arr);
System.out.println("After sort : " + Arrays.toString(arr));
}
}
Strings in Java
String:
String is a sequence of characters
String is an object in java.
Strings must represent with double quotes.
java.lang.String class providing pre-define methods to manipulate Strings.
Printing String:
class Code {
public static void main(String[] args) {
String s1 = "Hello";
String s2 = "World";
System.out.println("S1 : " + s1 + "\nS2 : " + s2);
}
}
length() : Instance method of String class returns the number of characters in specified string.
class Code {
public static void main(String[] args) {
String s = "amar";
System.out.println("Length of string : " + s.length());
}
}
Program to converting Character Array to String: We can pass array as input to String
constructor for this conversion.
class Code {
public static void main(String[] args){
char arr[ ] = {'a', 'm', 'a', 'r'};
String str = new String(arr);
System.out.println("String is : “ + str);
}
}
Program to convert String to Character array: toCharArray() method of String class returns
the character array with specified string characters.
class Code {
public static void main(String[] args) {
String str = "Hello";
char[] arr = str.toCharArray();
for(char x : arr){
System.out.println(x);
}
}
}
charAt(): String class instance method returns the character at specified index
class Code {
public static void main(String[] args) {
String s = "Hello";
System.out.println("char @ 2 is : " + s.charAt(2));
}
}
else
++symbols;
}
System.out.println("Alphabets : " + alphabets);
System.out.println("Digits : " + digits);
System.out.println("Symbols : " + symbols);
}
}
Immutable object:
Immutable object state(data) cannot be modified.
Immutable object state is constant.
Strings are Immutable in java.
If we modify String value, new String object will be created in different memory.
class Code {
public static void main(String[] args) {
String s1 = "Hello";
String s2 = "World";
s1.concat(s2);
System.out.println("s1 : " + s1);
System.out.println("s2 : " + s2);
}
}
We need to collect the new String object into any variable to use:
class Code {
public static void main(String[] args) {
String s1 = "Hello";
String s2 = "World";
s1 = s1.concat(s2);
System.out.println("s1 : " + s1);
System.out.println("s2 : " + s2);
}
}
Duplicate Strings: We cannot create multiple Strings with same value(duplicates). Same object
address will be shared to all String variables.
class Code {
public static void main(String[] args) {
String s1 = "Hello";
String s2 = "Hello";
System.out.println("s1 location : " + s1.hashCode());
System.out.println("s2 location : " + s2.hashCode());
}
}
class Code {
public static void main(String[] args) {
String s1 = "Hello";
String s2 = "Hello";
System.out.println("s1 location : " + s1.hashCode());
System.out.println("s2 location : " + s2.hashCode());
s1 = s1.concat("$");
System.out.println("s1 location : " + s1.hashCode());
System.out.println("s2 location : " + s2.hashCode());
}
}
String Literals:
Always store in String Pool area.
We can compare string literals either by using “==” operator or by using “equals()”
method.
class Code {
public static void main(String[] args) {
String s1 = "Hello";
String s2 = "Hello";
if(s1==s2)
System.out.println("Equal");
else
System.out.println("Not equal");
if(s1.equals(s2))
System.out.println("Equal");
else
System.out.println("Not equal");
}
}
String objects:
String objects get memory in heap area.
String object creates in heap area but the reference variable creates in Heap area.
We cannot use == operator to check the contents of String objects.
Note: It is always recommended to use equals() method to check the strings equality.
class Code {
public static void main(String[] args) {
String s1 = new String("Hello");
String s2 = new String("Hello");
if(s1==s2)
System.out.println("Equal");
else
System.out.println("Not equal");
if(s1.equals(s2))
System.out.println("Equal");
else
System.out.println("Not equal");
}
}
split(): split() is an instance method that returns String[] array of words after split.
class Code
{
public static void main(String[] args) {
String str = "this is core java online session";
String arr[ ] = str.split(" ");
}
}
String:
Immutable object – cannot be modified
Thread safe by default – as we cannot modify
StringBuffer:
Mutable object – hence we can modify the string
Synchronized by default – hence thread safe.
StringBuilder:
Mutable object – hence we can modify the string
Not Synchronized by default – hence not thread safe.
StringBuffer and StringBuilder has the same set of methods to process Strings:
class Code
{
public static void main(String[] args)
{
StringBuffer sb1 = new StringBuffer("Hello");
StringBuffer sb2 = new StringBuffer("World");
sb1.append(sb2);
System.out.println("sb1 : " + sb1);
Exception Handling
1. Compile time errors: Compiler raises error when we are not following language rules to
develop the code.
Every Method should have return type.
Statement ends with semi-colon;
Invoking variable when it is not present
2. Logical Errors: If we get the output of code instead of Expected contains Logical error.
Expected Result
1 12345
12 1234
123 123
1234 12
12345 1
3. Runtime Errors: Runtime Error is called Exception which terminates the normal flow of
program execution.
Handling invalid input by user
Opening a file which is not present.
Connect to database with invalid user name and password.
InputMismatchException: It occurs if user enter invalid input while reading through Scanner.
import java.util.Scanner;
class Code {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter 2 numbers : ");
int a = sc.nextInt();
int b = sc.nextInt();
int c = a+b;
System.out.println("Sum is : " + c);
}
}
Output:
Enter 2 numbers :
10
abc
Exception in thread “main” : java.util.InputMismatchException
catch block:
Exception object raised in try block can be collected in catch block to handle.
Handling InputMismatchException:
import java.util.Scanner;
import java.util.InputMismatchException;
class Code {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try{
System.out.println("Enter 2 numbers : ");
int a = sc.nextInt();
int b = sc.nextInt();
int c = a+b;
System.out.println("Sum is : " + c);
}
catch (InputMismatchException e){
System.out.println("Exception : Invalid input given");
}
}
}
void main(){
int[] arr = {10,20,30,40,50};
System.out.println(arr[5]);
}
void main()
{
String s = "abc";
int x = Integer.parseInt(s);
}
void main()
{
int a=10, b=0;
int c=a/b;
}
Exceptions Hierarchy:
Throwable is the super class of all exception classes.
We can handle only Exceptions in Java not Errors.
Try with Multiple Catch Blocks: One try block can have multiple catch blocks to handle
different types of exceptions occur in different lines of code.
Program to read 2 numbers and perform division: In this program, we need to handle two
exceptions
InputMismatchException: If the input is invalid
ArithmeticException: If the denominator is zero
import java.util.Scanner;
import java.util.InputMismatchException;
class Code {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
System.out.println("Enter 2 numbers : ");
int a = sc.nextInt();
int b = sc.nextInt();
int c = a/b;
System.out.println("Sum is : " + c);
}
catch (InputMismatchException e1) {
System.out.println("Exception : Invalid input values");
}
catch (ArithmeticException e2) {
System.out.println("Exception : Denominator should not be zero");
}
}
}
Finally block:
Finally, block is used to close resources (file, database etc.) after use.
Finally block executes whether or not an exception raised.
class Code
{
public static void main(String[] args)
{
try
{
// int a = 10/5 ; -> try-finally blocks execute.
// int a = 10/0 ; -> catch-finally blocks execute.
System.out.println("Try Block");
}
catch (Exception e)
{
System.out.println("Catch Block");
}
finally
{
System.out.println("Finally Block");
}
}
}
Checked Exceptions:
If the exception is not child of RuntimeException is called Checked.
Checked Exceptions occur when program connected to other resource.
Handling these exceptions is mandatory.
If we don’t handle the exception – Compiler raise Error message.
throws:
‘throws’ is used to describe the exception which may raise in Method logic.
Prototype of method specifies the Exception type.
We handle that exception when we invoke the method.
if(resource != null)
{
resource.close();
}
Custom Exceptions:
Defining a class by extending from Exception is called Custom Exception.
Examples:
o InvalidAgeException
o LowBalanceException
throw:
Pre-defined exceptions automatically raised when error occurred.
Custom exceptions must be raised manually by the programmer using throw-keyword.
InvalidAgeException:
import java.util.Scanner;
class InvalidAgeException extends Exception{
InvalidAgeException(String name){
super(name);
}
}
class Person{
static void canVote(int age) throws InvalidAgeException{
if(age>=18){
System.out.println("Can vote");
}
else{
InvalidAgeException obj = new InvalidAgeException("Invalid Age");
throw obj;
}
}
}
class Main{
public static void main(String[] args){
System.out.print("Enter age : ");
Scanner sc = new Scanner(System.in);
int age = sc.nextInt();
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 100
Practice @ www.onlinejavacompiler.com
try{
Person.canVote(age);
}
catch (InvalidAgeException e){
System.out.println("Exception : " + e.getMessage());
}
}
}
LowBalanceException:
import java.util.Scanner;
class LowBalanceException extends Exception {
LowBalanceException(String name) {
super(name);
}
}
class Account {
int balance;
Account(int balance) {
this.balance = balance;
}
class Bank {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter initial balance : ");
int amount = sc.nextInt();
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 101
Practice @ www.onlinejavacompiler.com
try {
acc.withdraw(amount);
}
catch (LowBalanceException e) {
System.out.println("Exception : " + e.getMessage());
}
System.out.println("Final balance : " + acc.balance);
}
}
import java.io.*;
class Code
{
public static void main(String[] args) throws Exception
{
try(FileInputStream file = new FileInputStream("Code.java"))
{
int ch;
while((ch=file.read()) != -1){
System.out.print((char)ch);
}
}
}
}
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 102
Practice @ www.onlinejavacompiler.com
Multi-threading
Multi-tasking:
We can implement multi-tasking in two ways.
o Program(process) based
o Sub program(thread) based.
class Code {
public static void main(String args[]) {
int x=10/0;
}
}
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 103
Practice @ www.onlinejavacompiler.com
Thread Life Cycle: Every thread has undergone different states in its Life.
New State: Thread object created but not yet started.
Runnable State: Thread waits in queue until memory allocated to run.
Running State: Threads running independently once they started.
Blocked State: The thread is still alive, but not eligible to run.
Terminated State: A thread terminates either by complete process or by occurrence of error
start():
An instance method of Thread class.
We must start the thread by invoking start() method on Thread object.
start() method allocates independent memory to run thread logic.
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 104
Practice @ www.onlinejavacompiler.com
sleep():
It is a static method define in Thread class.
It is used to stop the thread execution for specified number of milliseconds.
sleep() method throws InterruptedException
class Default
{
public static void main(String[] args)
{
First f = new First();
Second s = new Second();
f.start();
s.start();
}
}
class First extends Thread
{
public void run()
{
for (int i=1 ; i<=10 ; i++)
{
System.out.println("First : " + i);
try{
Thread.sleep(1000);
}catch(Exception e){ }
}
}
}
class Second extends Thread
{
public void run()
{
for (int i=1 ; i<=10 ; i++)
{
System.out.println("Second : " + i);
try{
Thread.sleep(1000);
}catch(Exception e){ }
}
}
}
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 105
Practice @ www.onlinejavacompiler.com
join():
An instance method belongs to Thread class.
It stops the current the thread execution until joined thread execution completes.
Consider First thread is calculating sum of first N numbers and second thread has to display
the result. The Second thread has to wait until First thread completes calculation.
import java.util.Scanner;
class Main {
static int n;
public static void main(String[] args) {
System.out.println("***Sum of First N numbers***");
Scanner sc = new Scanner(System.in);
System.out.print("Enter n val : ");
Main.n = sc.nextInt();
Calc thread = new Calc();
thread.start();
try{
thread.join();
}catch(Exception e){}
System.out.println("Sum value : " + Calc.sum);
}
}
class Calc extends Thread {
static int sum=0;
public void run() {
for (int i=1 ; i<=Main.n ; i++) {
Calc.sum = Calc.sum+i;
}
}
}
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 106
Practice @ www.onlinejavacompiler.com
Thread Synchronization:
Synchronization is the concept of allowing thread sequentially when multiple threads
trying to access the resource.
We implement synchronization using ‘synchronized’ keyword.
We can synchronize either Block or Method.
Consider a method increase the value of x by 1 and when multiple threads are trying to
invoke the method concurrently, we get odd results. Hence we need to synchronize the
value() method.
class Modify {
static int x;
synchronized static void value() {
x=x+1;
}
}
class First extends Thread {
public void run() {
for (int i=1 ; i<=100000 ; i++) {
Modify.value();
}
}
}
class Second extends Thread {
public void run(){
for (int i=1 ; i<=100000 ; i++) {
Modify.value();
}
}
}
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 107
Practice @ www.onlinejavacompiler.com
class Synchronization {
public static void main(String[] args) {
First t1 = new First();
Second t2 = new Second();
t1.start();
t2.start();
try{
t1.join();
t2.join();
}catch(Exception e){}
System.out.println("Final x value : " + Modify.x);
}
}
Syntax of Calling:
wait() notify() notifyAll()
synchronized( lockObject ) { synchronized(lockObject) { synchronized(lockObject)
while(!condition ) { //establish_the_condition; {
lockObject.wait(); establish_the_condition;
} lockObject.notify();
lockObject.notifyAll();
//take the action here; //any additional code }
} }
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 108
Practice @ www.onlinejavacompiler.com
IO Streams in Java
Introduction:
Stream is a sequence of data.
Java I/O is used to process and input and produce results.
The main types of streams are:
Byte Streams: are used to process 8-bit stream. We mostly use to process binary files.
Character Streams: are used to process 16-bit stream. We mostly use to process text files.
Console Streams: are used to authenticate users and passwords in Console based applications.
Buffered Streams: are used to process the data quickly.
Object Streams: are used to process objects information.
import java.io.*;
class Code {
public static void main(String args[]) throws Exception {
FileReader file = null;
try {
file = new FileReader("Code.java");
int ch;
while((ch=file.read())!=-1)
System.out.print((char)ch);
}
finally {
if(file !=null)
file.close();
}
}
}
import java.io.*;
class Code{
public static void main(String args[]) throws Exception{
FileReader src = null;
FileWriter dest = null;
try{
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 109
Practice @ www.onlinejavacompiler.com
Console Streams: The Java Console class is be used to get input from console. It provides
methods to read texts and passwords.
The following methods are used to read username and password in console-based
applications:
1. String readLine() : It is used to read a single line of text from the console.
2. char[] readPassword() : It is used to read password that is not being displayed on the
console.
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 110
Practice @ www.onlinejavacompiler.com
BufferedStreams:
Buffer is a temporary memory storage area.
Buffered Streams are used to process the information quickly.
We convert any data stream into buffer stream.
Object Streams: are used to perform read and write operations of Objects.
Serialization: Writing object information into a byte-stream.
De-Serialization: Converting byte-stream into object.
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 111
Practice @ www.onlinejavacompiler.com
transient:
Trasient is a keyword.
Transient variables will bot participate in serialization process.
Transient variables initialized with default values after De-Serialization.
Employee.java:
class Employee implements java.io.Serializable{
int id;
String name;
double salary;
transient int SSN;
Employee(int id, String name, double salary, int SSN){
this.id = id;
this.name = name;
this.salary = salary;
this.SSN = SSN;
}
}
Note: Compile the above file
Serialization.java:
import java.io.*;
class Serialization {
public static void main(String[] args) throws Exception{
FileOutputStream file = null;
ObjectOutputStream stream = null;
try{
file = new FileOutputStream("result.ser");
stream = new ObjectOutputStream(file);
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 112
Practice @ www.onlinejavacompiler.com
}
finally{
if(stream != null)
stream.close();
if(file != null)
file.close();
}
}
}
Note: Compile and Run the above code
De-Serialization.java:
import java.io.*;
class DeSerializatio{
public static void main(String[] args) throws Exception{
FileInputStream file = null;
ObjectInputStream stream = null;
try{
file = new FileInputStream("result.ser");
stream = new ObjectInputStream(file);
Marker Interface:
An interface without any abstract methods. For examples Serializable & Cloneable.
Marker interface provides information about extra behaviour of object to JVM such as
o Object can be Serializable
o Object can be Cloneable
Serialization process raises Exception if the class doesn’t implements Serializable
interface.
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 113
Practice @ www.onlinejavacompiler.com
Introduction:
Command Line is called CUI mode of OS.
We can pass arguments (input values) to the program from command line while invoking
the program.
main() method collects all these input values and store into String type array.
main(String[] args)
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 114
Practice @ www.onlinejavacompiler.com
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 115
Practice @ www.onlinejavacompiler.com
Packages
import: A keyword is used to import single class or multiple classes from package into java
application.
Syntax:
import package.*;
or
Import package.class;
lang package:
lang is called default package in java.
Without importing lang package, we can use the classes.
Examples System, String, Exception, Thread etc.
Random class: Random class belongs to util package and it is used to generate Random
numbers. We must import the class to use in our application.
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 116
Practice @ www.onlinejavacompiler.com
Code.java:
package student;
class Code
{
public static void main(String[] args)
{
System.out.println("Hello World!");
}
}
Syntax to compile:
cmd/> javac -d path filename.java
Example:
cmd/> javac -d . Code.java
Run the file: We need to specify the package name to run the class
cmd/> java student.Code
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 117
Practice @ www.onlinejavacompiler.com
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 118