Basics of Java
Basics of Java
void student()
{
……..
…….
//500 line of code
}
class student
{
void fee()
{
}
void lib()
{
}
void cse()
{
}
10 functions
Editions of Java
Each edition of Java has different capabilities. There are three editions of Java:
Java Standard Editions (JSE): It is used to create programs for a desktop computer.
Java Enterprise Edition (JEE): It is used to create large programs that run on the server and
manages heavy traffic and complex transactions.
Java Micro Edition (JME): It is used to develop applications for small devices such as set-top
boxes, phone, and appliances.
Types of Java Applications
There are four types of Java applications that can be created using Java programming:
Standalone Applications: Java standalone applications uses GUI components such as AWT,
Swing, and JavaFX. These components contain buttons, list, menu, scroll panel, etc. It is also
known as desktop alienations.
Enterprise Applications: An application which is distributed in nature is called enterprise
applications.
Web Applications: An applications that run on the server is called web applications. We use JSP,
Servlet, Spring, and Hibernate technologies for creating web applications.
Mobile Applications: Java ME is a cross-platform to develop mobile applications which run
across smartphones. Java is a platform for App Development in Android.
Java Platform
Java Platform is a collection of programs. It helps to develop and run a program written in the Java
programming language. Java Platform includes an execution engine, a compiler and set of
libraries. Java is a platform-independent language.
Features of Java
Simple: Java is a simple language because its syntax is simple, clean, and easy to understand.
Complex and ambiguous concepts of C++ are either eliminated or re-implemented in Java. For
example, pointer and operator overloading are not used in Java.
Object-Oriented: In Java, everything is in the form of the object. It means it has some data and
behavior. A program must have at least one class and object.
Robust: Java makes an effort to check error at run time and compile time. It uses a strong memory
management system called garbage collector. Exception handling and garbage collection features
make it strong.
Secure: Java is a secure programming language because it has no explicit pointer and programs
runs in the virtual machine. Java contains a security manager that defines the access of Java
classes.
Platform-Independent: Java provides a guarantee that code writes once and run anywhere. This
byte code is platform-independent and can be run on any machine.
Portable: Java Byte code can be carried to any platform. No implementation-dependent features.
Everything related to storage is predefined, for example, the size of primitive data types.
High Performance: Java is an interpreted language. Java enables high performance with the use
of the Just-In-Time compiler.
Distributed: Java also has networking facilities. It is designed for the distributed environment of
the internet because it supports TCP/IP protocol. It can run over the internet. EJB and RMI are
used to create a distributed system.
Multi-threaded: Java also supports multi-threading. It means to handle more than one job a time.
Freeware: Java is a freeware programming language.
Evolution or Version of Java:
Step 2) Next,
NOTE: You will be required to create an Oracle Account to start download of the file.
Step 4) Once the Java JDK 8 download is complete, run the exe for install JDK. Click Next
Step 5) Select the PATH to install Java in Windows… You can leave it Default. Click next.
NOTE: Follow the onscreen instructions in succeeding installation steps.
class first
{
public static void main(String args[])
{
System.out.println("Hello Java");
}
}
It is:
A specification where working of Java Virtual Machine is specified. But implementation
provider is independent to choose the algorithm. Its implementation has been provided by
Sun and other companies.
An implementation is a computer program that meets the requirements of the JVM
specification
Runtime Instance Whenever you write java command on the command prompt to run
the java class, an instance of JVM is created.
Platform Independency:
Escape sequences in Java
Keywords:
Identifiers:
An identifier is a sequence of one or more characters. The first character must be a valid first character
(letter, $, _) in an identifier of the Java programming language
There are certain rules for defining a valid java identifier. These rules must be followed, otherwise
we get compile-time error. These rules are also valid for other languages like C,C++.
The only allowed characters for identifiers are all alphanumeric characters([A-Z],[a-z],[0-
9]), ‘$‘(dollar sign) and ‘_‘ (underscore).For example “geek@” is not a valid java
identifier as it contain ‘@’ special character.
Identifiers should not start with digits([0-9]). For example “123geeks” is a not a valid java
identifier.
Java identifiers are case-sensitive.
There is no limit on the length of the identifier but it is advisable to use an optimum length
of 4 – 15 letters only.
Reserved Words can’t be used as an identifier. For example “int while = 20;” is an invalid
statement as while is a reserved word. There are 53 reserved words in Java.
class Main
{
public static void main(String[] args)
{
byte b1;
b1=13;
System.out.println(b1);
}
}
Memory representation:
b1
0 1 2 3 4 5 6 7
0 0 0 0 1 1 0 1
remainder
2 13 1
2 6 0
2 3 1
1 ---1
(13)10 = (1101)2
6 5 4 3 2 1 0
0*2 + 0*2 + 0*2 + 1*2 + 1*2 + 0*2 +1*2
0+0+0+8+4+0+1
Sign Bit
1) +ive 0
2) –ive 1
Range Calculation
Byte: 8 bits
Total values: 28 = 256
To find out max +ive & -ive values
256/2= +-128
128 (-ive values)
128 (+ive values)
1 (zero value)
257
b s
13 13
8 bits 16 bits
s b
13
16 bits 8 bits
Operator
Arithmetic Relational Logical Bitwise Assignment
+ < && & =
- > || | +=
* <= ! << -=
/ >= >> *=
% != >>> /=
++ == ^ %=
-- ~ &=
|=
<<=
>>=
^=
-- Decrement value by 1
Pre decrement Post decrement
X=10; X=10;
Y=--X; Y=X--
Y=9 Y=10;
X=9 X=9
Logical Operator: execute with Boolean value and generate a Boolean value
&&, ||, !
AND (&&)
boolean b1=true&&false; //false
boolean b1=true&&1; //error
Truth table
L R Result
T T T
T F F
F T F
F F F
OR (||)
boolean b1=true||false; //true
//boolean b1=true||11; //error
boolean b1=20<30||50>100; //true
L R Result
T T T
T F T
F T T
F F F
NOT (!)
true false
false true
boolean b1=!(30<40); //false
boolean b1=!(30>40); //true
int a=121&71;
64 32 16 8 4 2 1
121 1 1 1 1 0 0 1
71 1 0 0 0 1 1 1
1 0 0 0 0 0 1
Answer-> 65 64 0 0 0 0 0 1
OR (|)
int a=2|3 //3
0010
0011
0011
<< left shift
int a=12<<2; //48
8 4 2 1
(12)10 1 1 0 0
1 1 0 0 0 0
32 16 8 4 2 1
Direct Method: add number of zero at right side with binary of data
1100 (<<2, add 00 with this binary data) 110000
Right
int a=12>>2; //answer 3
1100
int a=12>>>2; //answer 3
(12)10 1 1 0 0
>> 1 1
>>> 0 0 1 1
^ XOR
L R result
1 1 0
1 0 1
0 1 1
0 0 0
101
110
011
~ complement operator
int a=~12; //-13
Sign Bit 8 4 2 1
0 1 1 0 0
Inverse + 1
1 1 1 0 1
int a=~ -12; //11
Sign 8 4 2 1
Bit
1 1 1 0 0
1’s Comp 0 0 1 1
+ (1) (1) 1
2’s Comp 0 1 0 0
0 Inverse 1 0 1 1
int a=2+3*5-20/4%3;
=2+15-20/4%3;
=2+15-5%3
=2+15-2
= 17-2
=15
int a=20*2-40%30*2
=40-40%30*2
=40-10*2
=40-20
=20;
Wrong method
int a=20*2-40%30*2
=40-40%60
=40-40
=0
++ Unary pre-increment
-- Unary pre-decrement
+ Unary plus
13 - Unary minus Right to left
! Unary logical negation
~ Unary bitwise complement
( type ) Unary type cast
* Multiplication
12 / Division Left to right
% Modulus
+ Addition
11 Left to right
- Subtraction
<< Bitwise left shift
10 >> Bitwise right shift with sign extension Left to right
>>> Bitwise right shift with zero extension
= Assignment
+= Addition assignment
-= Subtraction assignment
1 Right to left
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
Conditional Statement
1. If statement
2. If-else statement
3. Switch statement
Syntax of if statement
------
if(boolean)
{
-----
-----
}
-----
public class Main
{
public static void main(String[] args)
{
int a=10,b=20;
if(a>b)
{
System.out.println(a+" is largest number");
}
if(b>a)
{
System.out.println(b+" is largest number");
}
if(a==b)
{
System.out.println("Both numbers are equal");
}
}
}
Nested if statement
------
if(boolean)
{
-----
------
if(boolean)
{
-----
-----
}
-----
-----
}
-----
public class Main
{
public static void main(String[] args)
{
int a=10,b=20,c=30;
if(a>b)
{
if(a>c)
{
System.out.println(a+" is largest number");
}
}
if(b>a)
{
if(b>c)
{
System.out.println(b+" is largest number");
}
}
if(c>a)
{
if(c>b)
{
System.out.println(c+" is largest number");
}
}
if(a==b)
{
if(a==c)
{
System.out.println("All numbers are equal");
}
}
}
}
if-else statement
------
if(boolean)
{
-----
-----
}
else
{
-----
-----
}
1
22
333
While loop
initialization;
while(Boolean)
{
-------
inc/dec;
}
initialization;
while(Boolean)
{
-------
initialization;
while(Boolean)
{
-------
inc/dec;
}
inc/dec;
}
DO-While loop
initialization;
do
{
-------
inc/dec;
}
while(boolean);
Program
class abc
{
PSVM(String ar[])
{
int a;
a=11;
do
{
System.out.println(“Hello”);
a++;
}
while(a<=3);
}
}
Output:
Hello
Hello
Hello
initialization;
do
{
-------
initialization;
do
{
-------
inc/dec;
}
while(boolean);
inc/dec;
}
while(boolean);
class abc
{
PSVM(String ar[])
{
int a,b;
a=1;
do
{
b=1;
do
{
System.out.print(“*”);
a++;
}
while(b<=a);
a++;
System.out.println(“”);
}
while(a<=3);
}
}
*
**
***
for( ; ; )
{
System.out.println(“Hello”);
}
Break & Continue Keyword:
Break:
The break statement can also be used to jump out of a loop.
Continue:
The continue statement breaks one iteration (in the loop), if a specified condition occurs,
and continues with the next iteration in the loop.
for (int i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
System.out.println(i);
}
012356789
Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
int day = 4;
switch (day)
{
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Invalid choice");
}
// Outputs "Thursday" (day 4)
Array:
Arrays are used to store multiple values in a single variable, instead of declaring
separate variables for each value.
To declare an array, define the variable type with square brackets.
Types of array:
Processing Arrays
When processing array elements, we often use either for loop or
foreach loop because all of the elements in an array are of the
same type and the size of the array is known.
Example
Here is a complete example showing how to create, initialize,
and process arrays −
}
}
}
Output:
1 -2 3
-4 -5 6 9
7
Arguments
Return-Types
Object
Object Definitions:
An object is a real-world entity.
An object is a runtime entity.
The object is an entity which has state and behavior.
The object is an instance of a class.
The object a representative of a class
The object is a blue print of class
Object is nothing but a block of memory
Object Creation:
classname objectname=new classname()
Example of Class, Method & Object:
class demo
{ d1 d2 d3
void show()
{
show()
System.out.println("Hello User"); show() show()
}
}
class Main
{
public static void main(String ar[])
{
demo d1=new demo(); Output
demo d2=new demo();
Hello User
demo d3=new demo();
d1.show(); Hello User
d2.show(); Hello User
d3.show();
}
}
}
class Main
{
public static void main(String ar[])
{
arith a1=new arith();
a1.input();
a1.sum();
A1.sub();
}
}
import java.util.*;
class arith
{
int a,b,c;
void input()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter any two number");
a=sc.nextInt();
b=sc.nextInt();
}
void sum()
{
c=a+b;
System.out.println("Sum is "+c);
}
void sub(int p,int q)
{
c=p-q;
System.out.println("Sub is "+c);
}
int multi()
{
c=a*b;
return c;
}
float div(int p,int q)
{
return (float)p/q;
}
}
class Main
{
public static void main(String ar[])
{
arith a1=new arith();
a1.input();
a1.sum();
a1.sub(12,34);
int r=a1.multi();
System.out.println("multi "+r);
float r1=a1.div(12,5);
System.out.println("div "+r1);
}
}
Constructors in Java
In Java, a constructor is a block of codes similar to the method. It is called when an instance of the
class is created. At the time of calling constructor, memory for the object is allocated in the
memory.
It is a special type of method which is used to initialize the object.
Every time an object is created using the new() keyword, at least one constructor is called.
It calls a default constructor if there is no constructor available in the class. In such case, Java
compiler provides a default constructor by default.
There are two types of constructors in Java: no-arg constructor, and parameterized constructor.
Rules for creating Java constructor
There are two rules defined for the constructor.
Constructor name must be the same as its class name
A Constructor must have no explicit return type
A Java constructor cannot be abstract, static, final, and synchronized
Default Constructor:
class demo
{ d1 d2 d3
int a,b;
demo() a=10 a=10 a=10
{ b=20 b=20 b=20
a=10; show() show() show()
b=20;
}
void show()
{
System.out.println(a+" "+b);
} Output
}
10 20
class Main
10 20
{
public static void main(String ar[]) 10 20
{
demo d1=new demo();
demo d2=new demo();
demo d3=new demo();
d1.show();
d2.show();
d3.show();
d3.show();
}
}
Parametrized Constructor:
class demo
{ d1 d2 d3
int a,b;
demo(int p,int q) a=10 a=3 a=-1
{ b=20 b=8 b=-2
a=p; show() show() show()
b=q;
}
void show()
{
System.out.println(a+" "+b);
} Output
}
10 20
class Main
3 8
{
public static void main(String ar[]) -1 -2
{
demo d1=new demo(10,20);
demo d2=new demo(3,8);
demo d3=new demo(-1,-2);
d1.show();
d2.show();
d3.show();
}
}
x
import java.util.*;
class arith
{
int sum(int p[])
{
int c=0;
for(int i:p)
{
c=c+i;
}
return c;
}
}
class Main
{
public static void main(String ar[])
{
arith a1=new arith();
int a[]={11,22,33,44,55};
int r1=a1.sum(a);
System.out.println("result "+r1);
}
}
import java.util.*;
class arith
{
int a[]={11,22,33,44,55};
int[] sum()
{
return a;
}
}
class Main
{
public static void main(String ar[])
{
arith a1=new arith();
int r1[]=a1.sum();
for(int i:r1)
System.out.println(i);
}
}
Note: we can define multiple constructor in a class but parameter
should be different.
Parameters are differentiated by:
1. Numbers of parameters:
demo()
demo(int)
demo(int,int)
2. Types of parameters:
demo(int)
demo(char)
3. Order of parameters:
demo(int char)
demo(char,int)
import java.util.*;
class arith
{
int a[]={11,22,33,44,55};
int[] sum()
{
return a;
}
}
class Main
{
public static void main(String ar[])
{
arith a1[]=new arith[10];
/*int r1[]=a1.sum();
for(int i:r1)
System.out.println(i);*/
}
}
Object referencing:
class one o1/op/ox(t2) t1 t2
{ ox ox
int a,b; a=10,1000
void show() b=20,2000 a=1000 set()
{ show() b=2000 get()
System.out.println(a+" "+b); Show()
}
} set()
class two get()
{
one ox; Output
two() 10 20
{ 1000 2000
ox=new one(); 10 20
} 1000 2000
two(one op)
{
ox=op; class Main{
} public static void main(String ar[]){
void set() one o1=new one();
{ o1.a=10;
ox.a=1000; o1.b=20;
ox.b=2000; o1.show();
} two t1=new two();
void get() t1.set();
{ t1.get();
ox.show(); two t2=new two(o1);
} t2.get();
} t2.set();
t2.get();}}
Java – Static Class, Block, Methods and Variables
Static keyword can be used with class, variable, method and block. Static members belong to the class
instead of a specific instance, this means if you make a member static, you can access it without object.
Let’s take an example to understand this:
Here we have a static method myMethod(), we can call this method without any object because when we
make a member static it becomes class level. If we remove the static keyword and make it non-static then
we must need to create an object of the class in order to call it.
Static members are common for all the instances(objects) of the class but non-static members are separate
for each instance of class.
o The static variable can be used to refer to the common property of all objects
(which is not unique for each object), for example, the company name of
employees, college name of students, etc.
o The static variable gets memory only once in the class area at the time of class
loading.
o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance of a
class.
o A static method can access static data member and can change the value of it.
o static block used to initialize the static data member.
o static block is executed before the main method at the time of classloading.
class demo
{ d1 d2 d3
int a,b; a=100
a=1000
a=10
static int c;
void show()
{
System.out.println(a+" "+b+"
demo
"+c);
} c=0,30,300,3000
static void display() display()
{
System.out.println(c); Output
}
} 10 20 3000
class Main 100 200 3000
{ 1000 2000 3000
public static void main(String ar[])
3000
{
3000
demo d1=new demo();
3000
demo d2=new demo();
demo d3=new demo();
d1.a=10;
d1.b=20;
d1.c=30;//demo.c=30;
d2.a=100;
d2.b=200;
d2.c=300;
d3.a=1000;
d3.b=2000;
d3.c=3000;
d1.show();
d2.show();
d3.show();
d1.display();//demo.display();
d2.display();
d3.display();
}
}
import java.util.*;
class Main
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the details ");
int a=sc.nextInt();
if(a==11)
{
Main.main(args);
}
else
{
System.out.println("Input value is: "+a);
}
}
}
Example:
class SimpleStaticExample
{
// This is a static method
static void myMethod()
{
System.out.println("myMethod");
}
import java.util.*;
class bank
{
int cid;
String cnm;
float cbal,wm,dm;
static float bbal;
Scanner sc=new Scanner(System.in);
void get()
{
System.out.println("Enter customer id, name & balance");
cid=sc.nextInt();
cnm=sc.nextLine();
cnm=sc.nextLine();
cbal=sc.nextFloat();
bbal=bbal+cbal;
}
void show()
{
System.out.println("Customer id is: "+cid);
System.out.println("Customer name is: "+cnm);
System.out.println("Customer balance is: "+cbal);
}
void deposit()
{
System.out.println("Enter amount to be deposit");
dm=sc.nextFloat();
cbal=cbal+dm;
bbal=bbal+dm;
}
void withdraw()
{
System.out.println("Enter amount to be withdraw");
wm=sc.nextFloat();
cbal=cbal-wm;
bbal=bbal-wm;
}
static void showbankbal()
{
System.out.println("Current Bank balance is: "+bbal);
}
}
public class Main
{
public static void main(String[] args)
{
bank.showbankbal();
bank b1=new bank();
b1.get();
b1.show();
bank.showbankbal();
b1.withdraw();
bank.showbankbal();
b1.deposit();
bank.showbankbal();
bank.showbankbal();
bank b2=new bank();
b2.get();
b2.show();
bank.showbankbal();
}
}
Inheritance
The process by which one class acquires the properties(data members) and functionalities(methods) of
another class is called inheritance. The aim of inheritance is to provide the reusability of code so that a
class has to write only the unique features and rest of the common properties and functionalities can be
extended from the another class.
Parent/Base/Super
Class
Child/Derived/Sub
Class
Child Class:
The class that extends the features of another class is known as child class, sub class or derived class.
Parent Class:
The class whose properties and functionalities are used(inherited) by another class is known as parent class,
super class or Base class.
Inheritance is a process of defining a new class based on an existing class by extending its common data
members and methods.
Types of inheritance
Single Inheritance: refers to a child and parent class relationship where a class extends the another class.
Multilevel inheritance: refers to a child and parent class relationship where a class extends the child class.
For example class C extends class B and class B extends class A.
Hierarchical inheritance: refers to a child and parent class relationship where more than one classes
extends the same class. For example, classes B, C & D extends the same class A.
Multiple Inheritance: refers to the concept of one class extending more than one classes, which means a
child class has two parent classes. For example class C extends both classes A and B. Java doesn’t support
multiple inheritance, read more about it here.
Hybrid inheritance: Combination of more than one types of inheritance in a single program. For example
class A & B extends class C and another class D extends class A then this is a hybrid inheritance example
because it is a combination of single and hierarchical inheritance.
addition
int c
void sum()
input
int a,b
void inputdata()
addition
int c
void sum()
sqaure
int s
void srq()
addition substract
int c int d
void sum() void sub()
import java.util.*; class Main
class input {
{ public static void main(String args[])
int a,b; {
void input() addition a1=new addition();
{ a1.input();
System.out.println("Enter any two number"); a1.sum();
a=sc.nextInt(); substract a2=new substract ();
b=sc.nextInt(); a2.input();
} a2.sum();
}
class addition extends input }
{ }
int c;
void sum()
{
c=a+b;
System.out.println("sum="+c);
}
}
class substract extends input
{
int d;
void sum()
{
d=a-b;
System.out.println("sub="+d);
}
}
Constructor of Parent
Constructor of Child
class Parentclass
{
Parentclass(){
System.out.println("Constructor of parent class");
}
}
class Subclass extends Parentclass
{
Subclass(){
/* Compile implicitly adds super() here as the
* first statement of this constructor.
*/
System.out.println("Constructor of child class");
}
Subclass(int num){
/* Even though it is a parameterized constructor.
* The compiler still adds the no-arg super() here
*/
System.out.println("arg constructor of child class");
}
void display(){
System.out.println("Hello!");
}
public static void main(String args[]){
/* Creating object using default constructor. This
* will invoke child class constructor, which will
* invoke parent class constructor
*/
Subclass obj= new Subclass();
//Calling sub class method
obj.display();
/* Creating second object using arg constructor
* it will invoke arg constructor of child class which will
* invoke no-arg constructor of parent class automatically
*/
Subclass obj2= new Subclass(10);
obj2.display();
}
}
Output:
Constructor of parent class
Constructor of child class
Hello!
Constructor of parent class
arg constructor of child class
Hello!
class Parentclass
{
//no-arg constructor
Parentclass(){
System.out.println("no-arg constructor of parent class");
}
//arg or parameterized constructor
Parentclass(String str){
System.out.println("parameterized constructor of parent class");
}
}
class Subclass extends Parentclass
{
Subclass(){
/* super() must be added to the first statement of constructor
* otherwise you will get a compilation error. Another important
* point to note is that when we explicitly use super in constructor
* the compiler doesn't invoke the parent constructor automatically.
*/
super("Hahaha");
System.out.println("Constructor of child class");
}
void display(){
System.out.println("Hello");
}
public static void main(String args[]){
Subclass obj= new Subclass();
obj.display();
}
}
Output:
Polymorphism:
Polymorphism is one of the OOPs feature that allows us to perform a single action in different
ways. For example, lets say we have a class Animal that has a method sound(). Since this is a
generic class so we can’t give it a implementation like: Roar, Meow, Oink etc. We had to give a
generic message.
let’s get back to the point, when I say argument list it means the parameters that a method has: For
example the argument list of a method add(int a, int b) having two parameters is different from the
argument list of the method add(int a, int b, int c) having three parameters.
Three ways to overload a method
In order to overload a method, the argument lists of the methods must differ in either of these:
1. Number of parameters.
For example: This is a valid case of overloading
add(int, int)
add(int, int, int)
Program:
class DisplayOverloading
{
public void disp(char c)
{
System.out.println(c);
}
public void disp(char c, int num)
{
System.out.println(c + " "+num);
}
}
class Sample
{
public static void main(String args[])
{
DisplayOverloading obj = new DisplayOverloading();
obj.disp('a');
obj.disp('a',10);
}
}
Output:
a
a 10
class demo
{
void show(int a)
{
System.out.println("int: "+a);
}
void show(float a)
{
System.out.println("flloat: "+a);
}
}
public class Main
{
public static void main(String[] args)
{
demo d1=new demo();
d1.show(57);
d1.show(23.5f);
}
}
class demo
{
void show(int a)
{
System.out.println("int: "+a);
}
int show(int a)
{
System.out.println("flloat: "+a);
}
}
public class Main
{
public static void main(String[] args)
{
demo d1=new demo();
d1.show(57);
d1.show(23.5f);
}
}
Method Overriding
Declaring a method in sub class which is already present in parent class is known as method
overriding. Overriding is done so that a child class can give its own implementation to a method
which is already provided by the parent class. In this case the method in parent class is called
overridden method and the method in child class is called overriding method. In this guide, we
will see what is method overriding in Java and why we use it.
The purpose of Method Overriding is clear here. Child class wants to give its own implementation
so that when it calls this method, it prints Boy is eating instead of Human is eating.
class Human{
//Overridden method
public void eat()
{
System.out.println("Human is eating");
}
}
class Boy extends Human{
//Overriding method
public void eat(){
System.out.println("Boy is eating");
}
public static void main( String args[]) {
Boy obj = new Boy();
//This will call the child class version of eat()
obj.eat();
}
}
Output:
Boy is eating
class parent
{
void show()
{
System.out.println("Parent class method called...");
}
}
class child extends parent
{
void show()
{
System.out.println("Child class method called...");
}
}
class parent
{
void show()
{
System.out.println("Parent class method called...");
}
}
class child extends parent
{
void show()
{
super.show();
System.out.println("Child class method called...");
}
}
class ABC{
//Overridden method
public void disp()
{
System.out.println("disp() method of parent class");
}
}
class Demo extends ABC{
//Overriding method
public void disp(){
System.out.println("disp() method of Child class");
}
public void newMethod(){
System.out.println("new method of child class");
}
public static void main( String args[]) {
/* When Parent class reference refers to the parent class object
* then in this case overridden method (the method of parent class)
* is called.
*/
ABC obj = new ABC();
obj.disp();
class parent
{
void show()
{
System.out.println("Parent class method called...");
}
}
class child extends parent
{
void show()
{
System.out.println("Child class method called...");
}
}
class demo
{
int a;
void show()
{
System.out.println(a);
}
}
class Main
{
public static void main (String[] args)
{
demo d1=new demo();
d1.show();
d1.a=1000;
d1.show();
}
}
final class demo
{
final int a=10;
final void show()
{
System.out.println(a);
}
}
class Main
{
public static void main (String[] args)
{
demo1 d1=new demo1();
d1.show();
d1.show();
}
}
Abstract Class:
class that is declared using “abstract” keyword is known as abstract class. It can have abstract
methods(methods without body) as well as concrete methods (regular methods with body). A
normal class(non-abstract class) cannot have abstract methods. In this guide we will learn what is
a abstract class, why we use it and what are the rules that we must remember while working with
it in Java.
An abstract class can not be instantiated, which means you are not allowed to create an object of
it.
Abstract can be:
1. Class: can’t be instantiated
2. Method: methods without body, must be override
Program
abstract class abc
{
int a=10;
abstract void show();
}
class xyz extends abc
{
void show()
{
System.out.println("Value is: "+a);
}
}
class Main
{
public static void main(String ar[])
{
xyz x1=new xyz();
x1.show();
}
}
Program:
interface abc
{
int a=10;
void show();
}
interface xyz
{
int b=20;
void sum();
}
class pqr implements abc,xyz
{
public void show()
{
System.out.println(a+" "+b);
}
public void sum()
{
System.out.println(a+b);
}
}
class Main
{
public static void main(String ar[])
{
pqr p1=new pqr();
p1.show();
p1.sum();
}
}
interface xyz
{
int a=10;
void show();
}
interface pqr
{
int b=20;
void add();
}
class demo1 implements xyz,pqr
{
public void show()
{
System.out.println(a+" "+b);
}
public void add()
{
System.out.println("Sum is: "+(a+b));
}
}
class Main
{
public static void main (String[] args)
{
demo1 d1=new demo1();
xyz x1;
x1=d1;
x1.show();//dynamic method dispatching
pqr p1;
p1=d1;
p1.add();
}
}
Packages:
package as the name suggests is a pack(group) of classes, interfaces and other packages. In
java we use packages to or`ganize our classes and interfaces. We have two types of
packages in Java: built-in packages and the packages we can create (also known as user
defined package).
package mypackage; // package folder file
public class raj
{
public void show()
{
System.out.println("Package demo");
}
}
package letmecalculate;
public class Calculator {
public int add(int a, int b){
return a+b;
}
public static void main(String args[]){
Calculator obj = new Calculator();
System.out.println(obj.add(10, 20));
}
}
Now lets see how to use this package in another program.
import letmecalculate.Calculator;
public class Demo{
public static void main(String args[]){
Calculator obj = new Calculator();
System.out.println(obj.add(100, 200));
}
}
To use the class Calculator, I have imported the package letmecalculate. In the above
program I have imported the package as letmecalculate.Calculator, this only imports the
Calculator class. However if you have several classes inside package letmecalculate then
you can import the package like this, to use all the classes of this package.
import letmecalculate.*;
Example 2: Creating a class inside package while importing another package
As we have seen that both package declaration and package import should be the first
statement in your java program. Lets see what should be the order when we are creating a
class inside a package while importing another package.
//Declaring a package
package anotherpackage;
//importing a package
import letmecalculate.Calculator;
public class Example{
public static void main(String args[]){
Calculator obj = new Calculator();
System.out.println(obj.add(100, 200));
}
}
String:
String is a sequence of characters, for e.g. “Hello” is a string of 5 characters. In java, string
is an immutable object which means it is constant and can cannot be changed once it has
been created. In this tutorial we will learn about String class and String methods in detail
along with many other Java String tutorials.
Creating a String
There are two ways to create a String in Java
1. String literal
2. Using new keyword
String literal
In java, Strings can be created like this: Assigning a String literal to a String instance:
String str1 = "Welcome";
String str2 = "Welcome";
The problem with this approach: As I stated in the beginning that String is an object in
Java. However we have not created any string object using new keyword above. The
compiler does that task for us it creates a string object having the string literal (that we
have provided , in this case it is “Welcome”) and assigns it to the provided string instances.
But if the object already exist in the memory it does not create a new Object rather it
assigns the same old object to the new instance, that means even though we have two
string instances above(str1 and str2) compiler only created on string object (having the
value “Welcome”) and assigned the same to both the instances. For example there are 10
string instances that have same value, it means that in memory there is only one object
having the value and all the 10 string instances would be pointing to the same object.
What if we want to have two different object with the same string? For that we would need
to create strings using new keyword.
Length
import java.lang.*;
class Main
{
public static void main(String ar[])
{
String s1=new String("Ram Shrama");
int a=s1.length(); //int length()
System.out.println(a);
}
}
charAt
import java.lang.*;
class Main
{
public static void main(String ar[])
{
String s1=new String("Ram Shrama");
char a=s1.charAt(4);
System.out.println(a);
}
}
import java.lang.*;
class Main
{
public static void main(String ar[])
{
String s1=new String("Ram Shrama 123");
String a=s1.toUpperCase();
System.out.println(a);
import java.lang.*;
class Main
{
public static void main(String ar[])
{
String s1="ram";
String s2="Ram";
boolean b1=s1.equals(s2);
System.out.println(b1);
boolean b2=s1.equalsIgnoreCase(s2);
System.out.println(b2);
}
}
import java.lang.*;
class Main
{
public static void main(String ar[])
{
String s1="ram sharma";
String s2=s1.substring(4);
System.out.println(s2);
String s3=s1.substring(0,3);
System.out.println(s3);
}
}
import java.lang.*;
class Main
{
public static void main(String ar[])
{
import java.util.*;
class Main
{
public static void main (String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("enter any arithmetic expression");
String s=sc.next();
char op=s.charAt(2);
String s1=s.substring(0,2);
String s2=s.substring(3);
int a=Integer.parseInt(s1);
int b=Integer.parseInt(s2);
if(op=='+')
{
System.out.println("Sum is:"+(a+b));
}
if(op=='-')
{
System.out.println("Sub is:"+(a-b));
}
if(op=='*')
{
System.out.println("Multi is:"+(a*b));
}
if(op=='/')
{
System.out.println("Div is:"+(a/b));
}
if(op=='%')
{
System.out.println("Mod is:"+(a%b));
}
}
}
import java.util.*;
class Main
{
public static void main (String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("enter any arithmetic expression");
String s=sc.next();//234+3
int j=0;
char op=' ';
for(int i=1;i<s.length()-1;i++)
{
op=s.charAt(i);
if(op=='+'||op=='-'||op=='*'||op=='/'||op=='%')
{
j=i;
break;
}
}
String s1=s.substring(0,j);
String s2=s.substring(j+1);
int a=Integer.parseInt(s1);
int b=Integer.parseInt(s2);
if(op=='+')
{
System.out.println("Sum is:"+(a+b));
}
if(op=='-')
{
System.out.println("Sub is:"+(a-b));
}
if(op=='*')
{
System.out.println("Multi is:"+(a*b));
}
if(op=='/')
{
System.out.println("Div is:"+(a/b));
}
if(op=='%')
{
System.out.println("Mod is:"+(a%b));
}
}
}
import java.util.*;
class Main
{
public static void main (String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("enter any string");
String s1=sc.next();
System.out.println("enter any string");
String s2=sc.next();
int a=s1.length();
int b=s2.length();
if(a>b)
{
System.out.println(s1+" is greater length as compare to "+s2);
}
else if(b>a)
{
System.out.println(s1+" is greater length as compare to "+s2);
}
else
{
System.out.println("Both strings are equal");
}
}
}
import java.util.*;
class Main
{
public static void main (String[] args)
{
int i,j,l1,l2;
String s[]=new String[10];
Scanner sc=new Scanner(System.in);
System.out.println("enter any ten strings");
for(i=0;i<s.length;i++)
s[i]=sc.next();
for(i=0;i<s.length;i++)
{
for(j=i+1;j<s.length;j++)
{
l1=s[i].length();
l2=s[j].length();
if(l1>l2)
{
String t=s[i];
s[i]=s[j];
s[j]=t;
}
}
}
System.out.println("Sorted string according to length");
for(i=0;i<s.length;i++)
System.out.println(s[i]);
}
}
String Methods
Here is the list of methods supported by String class −
2. int compareTo(Object o)
Compares this String to another Object.
14. void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Copies characters from this string into the destination character array.
26. boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)
Tests if two string regions are equal.
27. boolean regionMatches(int toffset, String other, int ooffset, int len)
Tests if two string regions are equal.
import java.util.*;
class Main
{
public static void main (String[] args)
{
String s="Rama sharma Indore wale";
char x[]=s.toCharArray();
for(char i:x)
System.out.println(i);
boolean b=s.endsWith("Am");
System.out.println(b);
boolean b1=s.startsWith("1r");
System.out.println(b1);
int a=10;
String s1=String.valueOf(a);
System.out.println(s1);
float t=102.36f;
String s2=String.valueOf(t);
System.out.println(s2);
int a=s.indexOf('a');
System.out.println(a);
a=s.lastIndexOf('a');
System.out.println(a);
String x[]=s.split("ma");
for(String p:x)
System.out.println(p);
}
}
import java.util.*;
class Main
{
public static void main (String[] args)
{
String s1="ram";
String s2="Ram";
int a=s1.compareTo(s2);
System.out.println(a);
a=s1.compareToIgnoreCase(s2);
System.out.println(a);
}
}
/*
s1>s2 +ve
s1<s2 -ve
s1==s2 zero */
Let's try to understand the immutability concept by the example given below:
class Testimmutablestring{
public static void main(String args[]){
String s="Sachin";
s.concat(" Tendulkar");//concat() method appends the string at the end
System.out.println(s);//will print Sachin because strings are immutable objects
}
}
Output:Sachin
Now it can be understood by the diagram given below. Here Sachin is not changed but a new
object is created with sachintendulkar. That is why string is known as immutable.
As you can see in the above figure that two objects are created but s reference variable still refers
to "Sachin" not to "Sachin Tendulkar".
But if we explicitely assign it to the reference variable, it will refer to "Sachin Tendulkar"
object.For example:
class Testimmutablestring1{
public static void main(String args[]){
String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
}
}
Test it Now
Output:Sachin Tendulkar
In such case, s points to the "Sachin Tendulkar". Please notice that still sachin object is not
modified.
Why string objects are immutable in java?
Because java uses the concept of string literal.Suppose there are 5 reference variables,all referes to
one object "sachin".If one reference variable changes the value of the object, it will be affected to
all the reference variables. That is why string objects are immutable in java.
Constructor Description
StringBuffer() creates an empty string buffer with the initial capacity of 16.
StringBuffer(int capacity) creates an empty string buffer with the specified capacity as length.
public insert(int offset, String is used to insert the specified string with this string
synchronized s) at the specified position. The insert() method is
StringBuffer overloaded like insert(int, char), insert(int, boolean),
insert(int, int), insert(int, float), insert(int, double)
etc.
public delete(int startIndex, int is used to delete the string from specified startIndex
synchronized endIndex) and endIndex.
StringBuffer
public void ensureCapacity(int is used to ensure the capacity at least equal to the
minimumCapacity) given minimum.
public char charAt(int index) is used to return the character at the specified
position.
public int length() is used to return the length of the string i.e. total
number of characters.
public String substring(int is used to return the substring from the specified
beginIndex) beginIndex.
public String substring(int is used to return the substring from the specified
beginIndex, int beginIndex and endIndex.
endIndex)
import java.util.*;
class Main
String s=sc.next();
sb1.reverse();
String s1=sb1.toString();
if(s.equalsIgnoreCase(s1))
System.out.println("Palindrome string");
else
import java.util.*;
class Main
String s=sc.nextLine();
/* int a=sb1.capacity();
System.out.println(a);*/
System.out.println(sb1.deleteCharAt(3));
System.out.println(sb1.delete(0,3));
System.out.println(sb1.append("3"));
}
}
StringBuilder class
Java StringBuilder class is used to create mutable (modifiable) string. The Java StringBuilder class is same as
StringBuffer class except that it is non-synchronized. It is available since JDK 1.5.
Constructor Description
StringBuilder() creates an empty string Builder with the initial capacity of 16.
StringBuilder(int length) creates an empty string Builder with the specified capacity as length.
Method Description
public StringBuilder is used to append the specified string with this string. The append()
append(String s) method is overloaded like append(char), append(boolean), append(int),
append(float), append(double) etc.
public StringBuilder insert(int is used to insert the specified string with this string at the specified
offset, String s) position. The insert() method is overloaded like insert(int, char),
insert(int, boolean), insert(int, int), insert(int, float), insert(int, double)
etc.
public StringBuilder replace(int is used to replace the string from specified startIndex and endIndex.
startIndex, int endIndex, String
str)
public StringBuilder delete(int is used to delete the string from specified startIndex and endIndex.
startIndex, int endIndex)
public void ensureCapacity(int is used to ensure the capacity at least equal to the given minimum.
minimumCapacity)
public char charAt(int index) is used to return the character at the specified position.
public int length() is used to return the length of the string i.e. total number of characters.
public String substring(int is used to return the substring from the specified beginIndex.
beginIndex)
public String substring(int is used to return the substring from the specified beginIndex and
beginIndex, int endIndex) endIndex.
THREADING
Multi-threading
Def. concurrent running of multiple tasks within a program
A program may consist of many tasks that can run concurrently
A thread is a flow of execution from beginning to end of a task
Multiple threads run multiple CPUS
Multiple threads can share a single CPU--- known as time sharing
o The operating system is responsible for scheduling and allocating resources for
threads
Threading is an example of asynchronous programming
Multithreading can make your program more responsive and interactive, as well as
enhance performance
In java, each task is an instance of the Runnable interface, also called a runnable object
a thread is essentially an object that facilitates the execution of a task
major steps for creating a task, a thread, and starting the thread
public class Client
{
public void someMethod()
{
//create an instance of TaskClass
TaskClass task = new TaskClass(…);
//create a thread
Thread thread = new Thread(task);
//start the thread
thread.start(); //JVM will execute the task by invoking the task’s run method
…
} //end someMethod
} //end class Client
Example
Create a console program that has three tasks and three threads to run them.
The first task prints the letter a 100 times
The second task prints the letter b 100 times
The third task prints the integers 1 to 100
Example implementation
//create a TaskClass called PrintChar
public char PrintChar implements Runnable
{
private char charToPrint;
private int times;
//constructors
public PrintChar(char c, int t) {
charToPrint =c;
times =t; }
//overriding the run method to tell the system what task to perform
public void run()
{
for (int i = 1; i <= times; i++)
{
System.out.print(charToPrint + “ ”);
}
} //end class
//Create a TaskClass called PrintNum for printing numbers from 1 to n for a given n
public class PrintNum() implements Runnable
{
private int lastNum;
public printNum(int n) { lastNum = n;}
Thread class
public class Thread
{
//constructors
public Thread(){…} //creates an empty thread
public Thread(Runnable task) {…} //creates a task for a specific task
//methods
public void start(){…} /*starts the thread that causes the run method to be invoked by the
JVM*/
public Boolean isAlive() {…} //test whether the thread is currently running
public void setPriority(int i) {…} /*sets priority p (ranging from 1(lowest)j to 10 (highest)) for
the thread*/
public void join() {…} //waits for this thread to finish
public void sleep(long milliseconds) {…} /*puts a thread to sleep for a specified time in
milliseconds*/
public void yield() {…} /*causes the thread to pause temporarily and allow other threads to
execute*/
public void interrupt() {…} //interrupts this thread (will be discussed in upper div. classes)
}
There’s is another way to implement multithreading using the class thread instead of the runnable
interface (not recommended)
implementation of multiThreading using THREAD CLASs (Not recommended)
//CustomThread class
public class CustomThread extend Thread
{
…
Public CustomThread(…) {…}
//Client class
public class Client
{
…
public void doSomething()
{
…
CustomThread th = new CustomThread(…);
th.start();
…
}
}
Using yield()
public void run()
{
For (int i = 0; i< lastNum; i++)
{
System.out.print(“ “ + i);
Thread.yield();
}
}
Every time a number is printed, the thread of the print100 task is yielded. So each number is
followed by
some characters.
Using join()
forces one thread to wait for another to finish
public void run()
{
Thread t4 = new Thread(new PrintChar(‘c’, 40));
t4.start();
Try
{
for(int i = 0; i < lastNum; i++)
{
System.out.print(“ “ + i);
if( i==50)
{t4.join();}
}
} //end try
Catch (InterruptedException e) {
}
A new thread4 is created. It prints character c 40 times. The numbers from 50 to 100 are printed
after
thread thread4 is finished.
Thread Priority
If all runnable threads have the same priority, each is assigned an equal portion of CPU in
a circular queue. This is called a round-robin scheduling.
You can increase and decrease thread priority using the setPriority(int) method.
o 1 (lowest) – 10 (highest)
o You can also use int constants
MIN_PRIORITY = 1
NORM_PRIORITY = 5
MAX_PRIORITY = 10
o setPriority(5) and setPriority(NORM_PRIORITY) are equivalent
o The JVM always picks up the current runnable thread with the highest priority. A
lower priority thread can run only when no higher priority thread are running
Thread Pool
Creating tasks and threads we learned are not efficient
Runnable task1 = new Task(task);
Thread t = new Thread (task1);
t.start();
This approach is convenient for a single task execution but it isn’t efficient for a large
number of tasks because you have to create a thread for each task
o Starting a new thread for each task could limit the throughput and cause poor
performance
A thread pool is ideal to manage the tasks
o Java provides:
Executor interface- executing tasks in a thread pool
To create an executor object use the static methods in the
Executors class
ExecutorService interface- managing and controlling tasks
Executors Class
Methods
1. ExecutorService newFixedThreadPool (int numOfThreads)
2. ExecutorService newCachedThreadPool()
newFixedThreadPool
Creates a thread pool with a fixed number of threads executing concurrently. A thread might
be reused to execute another task after its current task is finished
newcachedthreadpool
Creates a thread pool that creates new threads as needed, but will reuse previously
constructed threads when they’re available
using a thread pool
Main
//create a fixed thread pool with a maximum of three threads
ExecutorService executor = Executors.newFixedThreadPool(3);
//submit runnable tasks to executor
executor.execute(new PrintChar(‘c’, 100));
executor.execute(new PrintChar(‘a’, 100));
executor.execute(new PrintNum(100));
Notes:
the executor creates three threads to execute three tasks concurrently
if we change the executor to create only one thread in the thread pool
if we use newCachedThreadPool
ExecutorService executor = Executors.newCachedThreadPool();
New threads will be created for each waiting task, so all the tasks will execute
concurrently
To shut down the executor uses the method shutdown
executor.shutdown();
class exp
{
public static void main(String ar[])
{
int a=0,b=0,c=0,d=0,e=0,f=0;
try
{
a=Integer.parseInt(ar[0]);
b=Integer.parseInt(ar[1]);
}
catch(ArrayIndexOutOfBoundsException ee)
{
System.out.println("Enter atleast two arguments");
}
catch(NumberFormatException ee)
{
System.out.println("String can't convert into integer");
}
c=a+b;
System.out.println("Sum= "+c);
d=a-b;
System.out.println("Sub= "+d);
try
{
e=a/b;
}
catch(ArithmeticException ee)
{
System.out.println("Zero can't divide any number");
}
System.out.println("Div= "+e);
f=a*b;
System.out.println("Multi= "+f);
}
}
class exp1
{
public static void main(String ar[])
{
int a=0,b=0,c=0,d=0,e=0,f=0;
try
{
a=Integer.parseInt(ar[0]);
b=Integer.parseInt(ar[1]);
e=a/b;
}
catch(Exception ee)
{
System.out.println("Wrong input value "+ee);
}
c=a+b;
System.out.println("Sum= "+c);
d=a-b;
System.out.println("Sub= "+d);
System.out.println("Div= "+e);
f=a*b;
System.out.println("Multi= "+f);
}
}
public class Main
{
public static void main(String[] args)throws Exception {
System.out.println("Hello World");
System.out.println(10/0);
Thread.sleep(1000);
System.out.println("Bye bye");
}
}
/*
1. reported/unchecked
2. unreported/checked
*/
import java.util.*;
public class Main
{
public static void main(String[] args)throws Exception {
Scanner sc=new Scanner(System.in);
System.out.println("Enter any number");
int a=sc.nextInt();
if(a==35)
{
ArithmeticException a1=new ArithmeticException();
throw a1;
}
else
{
System.out.println("Input value "+a);
}
}
}
import java.util.*;
class myexp extends Exception
{
public String toString()
{
String s1="This is user created & generated exception";
return s1;
}
}
public class Main
{
public static void main(String[] args)throws Exception {
Scanner sc=new Scanner(System.in);
System.out.println("Enter any number");
int a=sc.nextInt();
if(a==35)
{
try{
myexp a1=new myexp();
throw a1;
}catch(Exception ee)
{
System.out.println(ee);
}
}
else
{
System.out.println("Input value "+a);
}
}
}