0% found this document useful (0 votes)
23 views118 pages

Java Notes Full

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views118 pages

Java Notes Full

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 118

What is Java?

Java is a programming language and a platform. Java is not an acronym, its just a name.
Java is a high level, robust, secured and object-oriented programming language.

History
James Gosling, Mike Sheridan, Patrick Naughton initiated Java in 1991. Formerly called "Greentalk",
After which it was called "Oak". In 1995, it was named "Java".
JDK(Java Development Kit) 1.0 released.
In 2010 Oracle corporation brought Sun Microsystems

Features
1. Simple
2. Object Oriented
3. Secured
4. Platform Independent
5. Robust
6. Portable
7. Multi-threaded
8. Dynamic
9. Distributed
10. Interpreted
11. High Performance

Operating System Supported


1. Windows
2. Mac
3. Solaris
4. Linux

Installation Steps
Verification:
Go to Command Promt(Run -> cmd) type java to check whether java is installed or not.
Or Type javac
Command to check java version: java -version.
If java is already installed, usage of java will be displayed
else a message will be displayed as "java/javac is not recognised as internal or external command".

When will you get the “Java or Javac is not recognised as internal or external command’?
– If java is not installed at all
– If java is installed and not defined the path
If java is not installed, follow the below instructions

1. Download Java from "http://www.oracle.com/technetwork/articles/javase/index-jsp-


138363.html" official website based on your operating system.
2. Run the .exe file to install java on your machine, java will get installed.

Setting up path for Java

There are 2 ways to set java path:

1.temporary

2.permanent
1) How to set Temporary Path of JDK in Windows
To set the temporary path of JDK, you need to follow following steps:
Open command prompt
copy the path of jdk/bin directory
write in command prompt: set path=copied_path

set path=C:\Program Files\Java\jdk1.6.0_23\bin

2) How to set Temporary Path of JDK in Windows


1. Go to MyComputer properties
2. Click on advanced tab
3. Click on environment variables
4. Click on System variables
5. Write path of bin folder in variable value ( C:\Program Files\Java\jdk1.8.0_102\bin)
6. Click on OK.

To write java program we use:


1. Code or Text editors (Notepad, Notepad++, Edit plus, Text edit)
2. 2. IDE’s (Eclipse, IntelliJIdea, NetBeans) – Integrated Development Environment

What is complier?
Is a program that transforms source code written in a program language into BINARY format or
executable program.
Ex: C, C++, C# and Java.
What is Interpreter?
Executes the source code directly or translates the code one line at a time. These programs can
run on computer having interpreter. Interpreter do generate the binary code, but the code is never
compiled instead interpreted each & every time the program executes.

What is HLL(High Level Language)?


Programming language which are more understand by human and it is more natural language
element, easier, making the processor of developing program simple and understandable.
Ex: C, C++, C# and Java.

Sample Java Program


To compile and execute:
1. Write java program in notepad 2
2. Save the program with extension ‘.java’
Ex: If class name is Simple, then save it as Simple.java
3. Save it in a folder with your name (Preferable in a drive other than ‘C’)
4. Open cmd prompt and go to the specific folder using required commands.
5. You should be in the folder containing java program to compile and execute
6. We can use ‘javac’ command to compile and ‘java’ command to execute
Simple.java
class Simple
{
public static void main(String args[])
{
System.out.println("Hello World");
}
}
Programs written in Java should be saved in a file with .java extension. This file is known as Source file.
Source file (.java file) is fed to java compiler. The java compiler converts source code into ‘.class’ file.
This is an executable file and stored in byte code format called Class file.
The class files (.class) are automatically generated by the java compiler. The JVM (Java Virtual
Machine) understands only bytecode hence where ever JVM is available class files can be executed.

Understanding the Java Program


class – Keyword to specify/ create a class
public – Access specifier/modifier which specifies visibility.
Static – Keyword used to create static methods.
Advantage: No need of object creation to invoke static members. main method is executed by
jvm, so creation of objects is not required.
void – return type. void means nothing.
main – name of the method whicgh represents start of a program.
String[] args – used for Comamnd line arguments.
System.out.println() - print statement.

Compilation: (Command – Javac)


D:\Java programs>javac Simple.java
The source code written inside java file are converted into byte code (class file) by using a
command Javac. This Javac command is available in the bin folder where Java is installed.

D:\Java programs>java Simple


After compilation, the class files are generated in the default location where source code is available.
The class files can be executed by using a command ‘java’. This command is also available in bin
folder.
Note: While running the class file ‘.class’ extension should not be specified
Rules for saving a java file for learners:
1. Starting character of a class name should be in upper case (Industry Convention)
Ex: a. class Test (correct)
b. class testclass (in correct)
c. class TestClass (correct)

Note: When we are using multiple words for class name, every word first letter should be in caps
Ex: TestClass, MangoJuiceMixture.
2. Class name and file name when saving as .java should be same.

Operators
An operator is a symbol or character that allows a programmer to perform certain operations
like (Arithmetic and logical) on data and variables (Operands)
There are six types of operators are there
Arithmetic (+, -, *, /, %, ++, --)
Assignment (=, +=, -=, *=, /=, %=)
Relational (==, !=, <, >, <=, >=)
Logical (&, |, ^, !, &&, ||)
Conditional (?, ;)
Instanceof (instanceof)

Depending on the number of operators, operators can be of following three types.


Unary Operator: It takes operand such as ++X, Y--.
Here X and Y are variables where ++ and – are operators.
Binary Operators: It takes 2 operands such as X+Y, X-Y, X>Y etc.
Here X and Y are variables where +, - and > are operators
Ternary Operators: It takes 3 operands such as Z=X>Y?X:Y.
Here X, Y and Z are operands where ?, :, > are operators

Class Demo9
{
Static public void main(String…args)
{
Int i,j,k;
i=30;
j=20;
k=i+j;
System.out.println(“Sum of I and j is “+k);
//System.out.println(“Sum of ” + I + “ and” + j + “is “+k);
k=i-j;
System.out.println(“Difference of I and j is “+k);
k=i*j;
System.out.println(“Product of I and j is “+k);
// System.out.println(“Product of I and j is “+ (i*j));
k=i/j;
System.out.println(“Division of I by j is “+k);
// System.out.println(“Division of I by j is “+ (i/j));
int quotient= i/j
System.out.println(“Quotient of I by j is “+quotient);
double d = i/j; System.out.println(d); // output is – 1.0 (double type value)
d= 30.0/20.0; System.out.println(d); // output is – 1.5 (double type value)
d= 30/20.0; System.out.println(d); // output is – 1.5 (double type value)
d= 30.0/20; System.out.println(d); // output is – 1.5 (double type value)
System.out.println(30/20); // output is – 1 (int type value)
//K=30.0/20.0; // compile time error (cannot assign double to int directly) //
System.out.println(k);
int remainder = i/j;
System.out.println(Remainder of I by j is “ + remainder);
System.out.println(‘A’ + ‘B’);// output - 131, because it takes that characters Unicode values
System.out.println(‘A’ + “B”);// output – AB, because “B” is string. It will concatenate both
System.out.println(“A” + ‘B’);// output – AB, because “A” is string. It will concatenate both
System.out.println(“Hello” + ‘A’ + ‘B’);
// output – Hello AB, because “Hello” is string. It will concatenate all
System.out.println(‘A’ + ‘B’+ “Hello”);
/* output – 131 Hello, because first it will check left to right and takes first 2 characters and
checks whether they have any Unicode values and do that operation. Next it will concatenate this value
to string “Hello” value.*/
System.out.println(‘A’);
// output – A. prints char value
System.out.println(“A”); // output – A. prints string value
}
}
Note: int/int = int
int/double = double
double/int = double
double /double = double
Important notes:
Assignment operators:
The equal (=) symbol is the assignment operator. The assignment operator (=) is used to store
or assign a value to a variable
Simple assignment operator – example - i=10
In compound assignment operator we have (+=, -=, *=, /=)
Ex: i+=10 => i=i+10
i-=20 => i=i-20
i*=20 => i=i*20
i/=30 => i=i/30
i%=30 => i=i%30
Orange o1 = null; O1 = new Orange();

Class Demo9
{
static public void main(String…args)
{
Int i=2, j=3, k=4, l=25, m=7;
i+=5;
j*=6;
k/=2;
l-=10;
m%=5;
System.out.println(i);
System.out.println(j);
System.out.println(k);
System.out.println(l);
System.out.println(m);
}
}

Output is
7 18 2 15 2
Control statements
Helps in controlling the flow of the code.

2 types of statements.
1. Branch/Decision Statements
2. Loop Statements.

Branch/Decision Statements
Statements that allows you to create program where decisions are taken based on the
expression specified in the statement.

if statements
if – else statements
Nested if- else statements
Switch statements

public class Demo


{
public static void main(String args[])
{
int age = 16;
if(age<18)
{
System.out.println(“Not eligible to vote”);
}
}
}

if (true) // works

if(age=16) // compile time error, because we should not use assignment


operator(=).

if(age==16)// works
if(false) // works but no o/p. because the condition is false.

if(!false) // works and return o/p

if(false==false) // works and returns o/p Boolean var = true;

Note: we will see o/p when if condition is true. When the condition is false we will not see any o/p.

1. Block gets executed irrespective whether the condition is true or false as it become
independent.
2. When we mention the multi lines below to if statement and not mentioned braces, then only the
immediate next statement will consider for if condition if the results is true.
3. Other lines are considered as independent and they will execute as usual When we mention the
multi lines below to if statement and mentioned braces, then all the statements within the
braces will consider for if condition

Ex: if we change the age to 18 or more, then the next statements will not get executed.
Because the condition is false. The other lines will get executed and give o/p.
please find below program for the same

class Demo
{
public static void main(String args[])
{
int age=18;
if(age<18)
System.out.println(“not eligible to vote”);
age=age+2;
System.out.println(“age of person is” + age);
}

if – else statements

public class Demo22


{
public static void main(String args[])
{
int i=100, j=200;
if (i>j)
System.out.println(i+ “is greater than “+j);
else
System.out.println(j+ “is greater than “+i);
}
}

O/p – 200 is greater than 100.

Note: in the above if block, you have only one line. If you want multi lies, you have to use braces.
In else block, if you do not put braces ({}), will take first line. Other lines it will consider as
independent.

Note:
1. An if statement can be used without an else statement.
2. Multiple if else statements can be used in a program.
3. Once an if else statement causes an action in a program, then the remaining if else
statements will be ignored.

Nested if-else statements: When you have multiple conditions to be matched, we go with Nested if-
else statements.

import java.util.Scanner;
class Demo24
{
public static void main(String...args)
{
Scanner input=new Scanner(System.in);
System.out.println("Enter your marks");
int marks=input.nextInt();

if(marks>=0 && marks<50)


System.out.println("Fail");
else if(marks>=50 && marks<65)
System.out.println("Pass");
else if(marks>=65 && marks<75)
System.out.println("First class");
else if(marks>=75 && marks<=100)
System.out.println("Distinction");
else
System.out.println(“Invalid value”);
Switch case statement
The switch case statement is used to select an action from a given set of actions, based on a specified
expression.
Syntax: Switch (expression/ variables)
{
Case value 1: statements
break;
Case value 2: statements
break;
Case value 3: statements
break;
Default: default statement;
}

import java.util.Scanner;
class switchDemo
{
public static void main(String...args)
{
Scanner sc = new Scanner(System.in)
SOP(“Enter your atomic number”);
int atomno = sc.nextInt();
final int x=34;// we can use only constant variables. When we use keyword final means, it is a
constant value
switch (atmno)
{
default: SOP(“Invalid no”);
break;
case 1: SOP(“Hydrogen”);
break;
case 2: SOP(“Helium”);
break;
case 3: SOP(“Lithium”);
break;
case 8: SOP(“Oxygen”);
break;
case x: // here ‘x’ is a constant variable declared as final in above line and the value is 34.
SOP(“Selenium”);
break;
}
}
}

The expression/ variable in the preceding code snippet can be any expression depicting a char, byte,
short, int or enum variable.
The switch case also support some wrapper classes like integer, byte, short

NOTE: We have to use ‘break’ statement in each case, otherwise it will executes next line till it finds
break statement or end of the program.

NOTE: Default statement when we use at end, we need not to write break statement, because it is at
the end. If we use starting of the program, we have to use break statement to stop the flow.

Question:

When can we use if else and switch case?


If statements are used to evaluate Boolean expression. A switch statement allows a variable to be
tested for equality against a list of values. Each value is called a case and the variable being switched
on is checked for each other. When we range of values, relational operators or logical operators, then
we can use if else.

If we are using only values (list of values or 1-1 mapping) then we go for switch case.

Loop statements
Loops are statements preferably with braces where the code in the block ({}) gets executed certain
number of times based on the condition.

For loop
It is initialized first and then the Boolean expression is checked.
If the expression evaluates to true, then the for block is executed, otherwise the loop terminates.
If the for block is executed, then the increment or decrement expression is updated to continue loop.

Synatx: For (initialization;condition;update)


// if we put ; at the end of line, it means it will end the statement and no further
loop will be executed. That line is independent. { //body }

The 3 parts of the for loop – initialization, expression and update, must be separated by semicolon (;).
Or else the program will lead to a compile error.
public class Demo
{
public static void main(String args[])
{
for(int i =1; i<=20;i++)
{
System.out.println(i);
}
}
}

while loop:

verifies the condition, if condition returns true, it enters into the body of the while, it executes all the
statements after executing last statement. It verifies again whether the condition, it iterates until
condition becomes false.

NOTE: while is an infinte loop

Syntax:
initialization
while(condition)
{
statements
increment/decrementation
}
Note: While loop can be used with non numeric conditions also. Like checking a character in a variable
or checking for a string value in a variable

import java.util.Scanner;
class WhileDemo
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
Char ch = ‘n’;
String ans = “”;
while (ch!=’y’)
{
System.out.println(“Will you listen to me?”);
Ans = input.nextLine();
Ch = ans.charAt(0); // used to convert chart at ‘0’ place to lowercase
}
}
}

Do while

Do while loop works similar to while loop. But the difference is do while loop block executes at least
once irrespective of whether the expression evaluates to true a false (while loop, is an entry check loop
and do while is an exit check loop)

public class Demo26


{
public static void main(String args[])
{
int i=1;
do
{
System.out.println(i++);
}
while(i<=20);
}
}

What is the difference b/n for loop and while/ do while loop?
1. For loop checks for numeric conditions and have definite iterations
2. While or do while loop can have both numeric and non numeric conditions
3. It has definite iterations with numeric condition and not finite iteration with non numeric
conditions.

JUMP Statements

break, continue and return statements


break: terminates the execution of whole loop in decision or iterational statements

public static void main(String args[])


{
for( int i=0;i<5;i++)
{
if(i==3)
break;
System.out.println( “i = “ +i);
}
}
}

Labeled break statement : It is used only in nested decisional or iterational statements. A label in a
labeled break statement is similar to an identifier which is used before the loop. This identifier is always
followed by a colon(:)

public static void main(String args[])


{
for( int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
if(i==j)
break;
System.out.println( “i = “ +i +” ” +”j = ” +j);
}
}
}

Note: If break is used without label, it exits only inner loop. If labeled break is used, outer for loop will
be terminated.

Continue Statement:
In unlabeled statements, the continue statement causes the current iteration of a loop to stop and
continue with the next iteration. However, in labeled statements the continue statements stops the
current iteration of outer loop and continue with next iteration.
public class Demo
{
public static void main(String args[])
{
for(int j=0; j<10; j++)
{
if (j==6)
{
continue;
}
System.out.println(j);
}
}
}

O/p: o/p – 0 2 4 8

Using labeled continue statements

public class Demo31


{
public static void main(String args[])
{
int j,k;
demo:
for (j=0; j<5; j++)
{
for (k=2;k<5;k++)
{
if (j==6)
{
Continue demo;
}
System.out.println(“j= “ + j + “k= “ + k);
}
}
}
}
Return statement
Causes the control of execution to return the caller of a method. While using the return
statement, you must be careful about the return type of the method. If the method is of the void type
you should not use return or use just return.
[will be studied while discussing methods]

BASIC JAVA PROGRAMS


1. Program to find the factorial of a number
class Factorial
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in)
SOP(“Enter any number”);
int n = sc.nextInt();
int fact=1;
for(int i=1;i<=n;i++)
{
fact = fact*i;

}
System.out.println("Factorial of " +fact + " = " +fact);
}
}

2. Program to find the fibanocci Series


class fibanocci
{
public static void main(String args[])
{
int f1=0,f2=1;
Scanner sc = new Scanner(System.in)
SOP(“Enter the range”);
int range = sc.nextInt();
int next=0;
System.out.println("Fibanocci Series: " + f1 + " " +f2 );
for (int i=3; i <= range;++i)
{
next = f1 + f2;
f1 = f2;
f2 = next;
System.out.print(" " +next);
}
}
}

3. Program to print the tables from 1 - 20


class Tables
{
public static void main(String args[])
{

int prod=0;
for(int i=10;i<=20;i++)
{
for(int j=1;j<=10;j++)
{
prod = i*j;
System.out.println(i +"*"+j+"="+prod);
}
System.out.println("_________________________");
}
}
}

4. Program to print odd numbers from 151 to 131 (reverse order)


class oddNumbers
{
public static void main(String args[])
{
int i =151;
System.out.println("Odd Numbers from 151 to 131");
while(i>131)
{
if(i%2==1)
System.out.println(i);
i--;
}
}
}

5.Program to print the number in below pattern


1
22
333
4444
55555

public class pyramid


{
public static void main(String args[])
{
for(int i=0; i<5; i++)
{
for(int j = 0;j<=i;j++)
{
System.out.print(i+1);
}
System.out.print("\n");
}
}

JAVA OOPS CONCEPTS

Object oriented programming language – programming language is a methodology or paradigm to


design a program using classes and objects. It simplifies the software development and maintenance
by providing some concepts such as:
1. Class
2. objects
3. Inheritance
4. Abstraction
5. Polymorphisn
6. Encapsulation
class: A blueprint/ logical entity which is a collection of objects and its behavior

Object: Any entity that has a state and behavior


It is an instance of class. Real world entity.
Ex: Student, employee, Chair, Table

Inheritance
When one object acquires all the properties and behavior of a parent object i.e known as
Inheritance.
Provides code re-usability.
used to achieve run-time polymorphism
Polymorphism
When one task is performed by different ways i.e known as polymorphism.
Method overloading and method overriding are 2 ways to achieve this.

Abstraction
Hiding internal details and showing functionality. Abstract class and interface are used to achieve
this.

Encapsulation
Binding/wrapping up of data and behavior together in a single unit is called Encapsulation
Ex: Java class

Advantages of OOPS
1. makes development and maintenance easier
2. provides data hiding mechanism
3. Easy to simulate real world event more effectively.

NOTE: Object based programming language follows all features except inheritance.
Ex: Javascript and VBScript.

Naming Conventions:

1. Class name should start with Uppercase and follow camelcase pattern(MyFirstClass)
2. Interface name should start with uppercase and follow camelcase pattern(MyFirstInterface)
3. variable name should start with lowercase and follow camelcase pattern (studentName)
4. package name with lowercase(java, lang, util)
5. Class names must begin (first letter) with a letter, an underscore ( _ ) or a dollar sign ($)
6. From second character, class names may contain a letter, digits, an underscore ( _ ) or a dollar
sign ($)
7. Class names cannot be a keyword (Java keyword)
8. Class name cannot have space between the words

Understanding of variables
• Variable can be classified as instance variables, local variables and static variables
• The variable declared within a method or a block is called local variables.
• The variables declared within a class is called class level variables/instance variables or fields.
• In class level scope you can make them as static or non static.
• If you add static keyword for declaration then these variable become static variables .
• If you don't use static keyword these variable become non static variables/instance variables.
• You cannot make static or non static in local scope.
• Local variable declared in one method or a block cannot be accessed in another method or a
block.

CONSTRUCTORS
• constructors are special member of a class which is used to initialize the object.
• Invoked at the time of object creation
• It constructs the values i.e provides data for the object
• every class defined in java should have a constructor either compiler defined or user defined.
• Constructor defined by the compiler is called default constructor which provides default
initialization for member variables.
• Compiler defines a constructor when there is no constructor defined by the user explicitly.
• Programmer can define 2 types of constructor, no-argument constructor and parametrized
constructor.
• Constructor with parameters are known as parametrized constructor.
• The benefit of parametrized constructor is the object can be initialized with user provided values
at runtime
• While defining a constructor, constructor name should be same as class name
• Constructor should not have any return type.
• Body of constructor should be exclusively used to initialize instance members
• Constructors can have access specifiers such as public, private, protected and default.
• Constructors should have access specifiers such as final, static, abstract and synchronized.
• Constructor can throw exception
• It can contain all legal java keywords except return statement.
• Class can have same name for constructor and methods
• If a constructor is created with parameters, then we should use that constructor with
arguments to construct objects.
Ex: Non - argument constructor
class Sample
{
int i,j; //declaring instance variables
Sample() //non-argument constructor
{
i=10; //initializing instance members
j=20;
}
}

class Demo
{
public static void main(String args[])
{
Sample s1 = new Sample(); //Instantiating class /creating object
System.out.println(s1.i); //utilization of instance variables with the help of objects
System.out.println(s1.j);
}
}
Drawback: all the objects would be constructed with the same values of i and j.

Ex: Parametrized constructor

class Parameters
{
int I;
Parameters(int a)
{
i=a;
}
}

class ParamDemo
{
public static void main(String args[])
{
Parameters p1 = new Parameters(23);
System.out.println(p1.i);
Parameters p3 = new Parameters(35);
System.out.println(p3.i);
}
}

NOTE: If the class contains only parametrized constructors then we cannot use default constructor to
create objects.

Constructor overloading
when we have more than one constructor for a class with different signature is called Constructor
overloading. This can be achieved based on number of parameters, datatype of the parameters and
sequence of each parameters.

Class A
{
int i,j;
long l;
String a ,b;

A(int x,int y)
{
i=x;
j=y;
}

A(int x, long d)
{
i =x;
l =d;
}

A(String s, int p)
{
a=s;
b=p;
}
A(int p, String s)
{
i=p;
a=s;
}
}

classs Demo
{
public static void main(String args[])
{
A a1= new A(100,200);
System.out.println(a1.i);
System.out.println(a1.j);

A a2 = new A(“Star”, 20);


System.out.println(a2.a);
System.out.println(a2.i);
}
}

Note: Constructor overloading provides flexibility to end user. Based on their need, thery can use
specific signature of the constructor.

Questions:
1. Does constructor return any value?
Yes, it returns current class instance, but we cannot use return type, yet it returns a value.
2. Can constructor perform other tasks instead of initialization?
Yes, like object creation, starting thread, calling method etc. Any operation can be performed in a
constructor like method.

Disadvantages/Limitations

1. to perform any calculations on different parameters 'n' number of instances are to be created.
2. User gets confused/cannot understand the behavior or functionality if each constructor.

To overcome these limitations we go with methods.


Methods
A method describes the behavior or actions that can be performed by an object or a class.

Syntax: modifiers returntype name(parameters_list)


{ //method body
}
modifier – Access type/behavior of a method (optional)
return type - type of data a method can return (void/primitive datatypes)
name of the method – any meaningful name apart from keywords
parameter list - type, order and number of datatype/variables a method utilizes(optional)
Method body - what operation a method should/is to perform.

Types:
1. Method without return type and without parameters
2. method without return type and with parameters
3. Method with return type and without parameters
4. Method with return type and with parameters

Note:
• If method doesn't return anything, use void
• Skip/don't use return in case of void
• To call the method, use proper method name.
• Write method in class definition block
• If return type is void and a value is returned it results in compilation error.
• Method can return void, primitive type, object or an array/collection.

public class Demo19


{
static void print()
{
System.out.println("I love java and selenium");
return; //optional, since void is the return type
}

static int sum (int n1, int n2)


{
int total = n1+n2;
return total; // returns int
}

static double avgTemp(double t1, double t2)


{
double avg = (t1+t2)/2.0 ;
return avg;
}

static String wish (String name)


{
return "Hello"+ name;
}

public static void main(String[] args)


{

print(); // calling ‘print’ method


int total=sum(10,20);// o/p is stored in a variable
System.out.println(total);
System.out.println(sum(100,200)); //o/p is input to println
sum(123,456); //we will not get any o/p, because no method defined for this
System.out.println(sum(sum(123,456), sum(111,222)));
//o/p is sum of first inner method and second inner method. Now these will acts as input to other sum
method
System.out.println(avgTemp (22.6, 26.4));
System.out.println(wish("Lolly"));
}
}

JAVA STATIC COMPONENTS


Static members are used for memory management mainly. Memory will be allocated for static
components at run time.
Variables, methods, blocks, nested classes etc can be made as static.
Static components belong to class than objects.

Class Student
{
int roll;
String name;
static String college = “Oxford”;

Student(int r, String n)
{
roll = r;
name = n;
}

void display()
{
System.out.println(“Roll_no = “ + roll);
System.out.println(“Name = “ +name);
System.out.println(“College = “ + college);
}
}

class StudentDemo
{
public static void main(String args[])
{
Student s1= new Student(01, “Hema”);
Student s2 = new Student(02, “Ram”);
s1.display();
s2.display();
}
}
Note:
• Any static components can be directly accessed within static block or static method.
• Static variables and methods can be directly accessed within constructor and instance methods.

Order of execution when static block is present.

Class StaticDemo
{
StaticDemo()
{
System.out.println(“Constructor”);
}
static
{
System.out.println(“Static block”);
}
}

class Demo
{
public static void main(String args[])
{
StaticDemo s= new StaticDemo();
}
}

All static components will be loaded into the memory first. So creation of object, executes the static
block within the class and then executes the corresponding constructor.

//Program to check the usage of static variables


class StaticDemo
{
static int count=0;
StaticDemo()
{
count++;
}
}
class Demo
{
public static void main(String args[])
{
StaticDemo s1 = new StaticDemo();
StaticDemo s2 = new StaticDemo();
System.out.println(s1.count);
System.out.println(s2.count);
}
}
This keyword
this is a reference variable that refers to the current object.
6 ways "this" can be used.
• this can be used to refer current class instance variable.
• This can be used to invoke current clas method
• this() can be used to invoke current class constructor.
• this can be used as an argument in the method call.
• this can be used to return the current class instance from the method
• this can be used as an argument in the constructor call.

Ex: Student(int roll, String name)


{
this.roll = roll;
this.name = name;
}

To invoke current class method

class A
{
void m()
{
System.out.println("hello m!");
}
void n()
{
this.m();
}
}

class Demo
{
public static void main(String args[])
{
A a = new A();
a.n();
}
}
this() : to invoke current class constructor for re-using the constructor called as Constructor- chaining.

Class A
{
A()
{
System.out.println("Hello A");
}
A(int x)
{
this();
System.out.println(x);
}
}

class Demo
{
public static void main(String[] args) (String args[])
{
A a = new A(10);
}
}

NOTE: this should be the first statement in any block.

This: to pass as an arg in the method


class Sample
{
void m(Sample obj)
{
System.out.println("method is invoked");
}
void p()
{
m(this);
}
}
public static void main(String[] args) (String args[])
{
Sample s= new Sample();
s.p();
}
}

INHERITANCE

• Inheriting all the members of parent class to the child class other than private members is
known as inheritance.
• The parent class is called a super class/base class whereas the child class is known as
subclass/derived class.
• A sub class inherits all the members (both static and non-static) (fields, methods and nested
classes) from its super class except private members.
• Constructors are not members, so they are not inherited by subclasses, but the constructor of
the super class can be invoked from the subclass
• The inheritance can be achieved by using keyword extends.
• The subclass should extend the superclass
• With the reference of subclass object we can access both the inherited member as well as
subclass member
• Multilevel inheritance are supported in java
• Multiple inheritance are not allowed in java through classes.

2. Hierarchial Inheritance

Types of Inheritance
1. Single Inheritance
4. Class A

2. Multilevel Inheritance
4. Multiple Inheritance
5. Hybrid Inheritance
{
Int i=100;
Static int j = 200;
Private int k=300; // does not get inherited, because it is private
Void print()
{
System.out.println(“i= “ + i);
}
Static void disp()
{
System.out.println(“j= “ + j);
}
}

Class B extends A
{
}
Class InheritDemo
{
public static void main(String args[])
{
B b1 = new B();
b1.print();
System.out.println(b1.i);
System.out.println(“----”);
B.disp();
System.out.println(B.j); System.out.println(“------”);
b1.disp();// compiler will replace b1 with class
B. System.out.println(b1.i); // compiler will replace b1 with class B
// System.out.println(b1.k); // private members are not inherited
}
}

Note:
1. we can access static members through a reference variable.
Compiler replaces the reference variable with its type like Compiler does the follwoing
b1.j – B.j 2
2. Non static members cannot be accessed through a class name.
Class X
{
X(String s)
{
}
}

Class Y extends X
{
Y()
{
Super(“Fellow”);
}
}
Class Demo49
{
public static void main(String args[])
{
X x1 = new X(“Hello”);
Y y1 = new Y();
}
}

Note: When compiler creates a constructor its capacity is only


1 – To create a default constructor i.e. constructor without argument
2 – To put “Super” without any arguments in the constructor
Notes: Super class has user defined constructor with 1 or more arguments, then we have to create the
subclass constructor compulsorily and call super (argument) as expected by super class constructor.
Class G
{
}
Class H extends G
{
H (int a, int b, int c);
{
Super ();
// this will be put by compiler by default.
// Since super class does not have a constructor,
// it will first create a default constructor in the super class and in sub class uses super ();
}
}

Class Demo
{
public static void main(String args[])
{
G g1 = new G();
H h1 = new H(100, 200, 300);
}
}

Note:
• We cannot have 2 variables with the same name - one static and another non-static.
• We cannot have 2 variables with the same name - one local and another method parameter.
• We can have 2 variables with the same name - one static and another local.
• We can have 2 variables with the same name – one non-static and another local.
• We cannot have 2 variables with the same name – one local and another within static block.

class C
{
int i,j;
C(int i,int j)
{
this.i=i;
this.j=j;
}
void print()
{
System.out.println("i="+i);
System.out.println("j="+j);
}
}

class D extends C
{
int a,b;
D(int a,int b)
{
super(a,b);
this.a=a;
this.b=b;
}
void disp()
{
System.out.println("a="+a);
System.out.println("b="+b);
}
}
class E extends D
{
E()
{
super(555,666);
}
E(int x,int y)
{
super(x,y);
}
}

class Demo
{
public static void main(String...args)
{
C c1=new C(100,200);
c1.print();
System.out.println("---------");
D d1=new D(300,400);
d1.disp();
d1.print(); System.out.println("---------");
E e1=new E();
e1.disp();
e1.print();
System.out.println("---------");
E e2=new E(500,600);
e2.disp();
e2.print();
}
}

Interview question:
what is the difference b/n parameter and argument?
Parameters refers to the definition of a method or constructor or exception to which we intend to
pass values or variables
Ex: Static int add(int n1, int n2)
{
}
Here n1 and n2 are parameters.

Arguments refers to values or variables which we actually pass when calling the method or a
constructor
Ex: add (100,200) , Here 100 and 200 are arguments.

NOTE:
1. If a class contains more than one constructor we can call any one of the constructor to create
an object.
2. If super class contains more than one constructor we can call any one of the super class
constructor available in the super class from subclass.
3. When we use ‘Super ()’ to call super class constructor it should be the first statements in the
subclass constructor.
Why do we need to create our own constructor?
If we need to create an object of a class based on specific criteria then we need to create our
own constructors.
Ex: If we need to create object of student class which takes name and student id or name and
mail id then create our own constructor

Class A
{
A(int a)
{
}
A()
{
}
}

Class B extends A
{
public static void main(String args[])
{
}
}
// compiler automatically put B () constructor and add super ().
This will work as the super class has a no argument constructor.

Notes:
• Every class we create in java will be sub class to the Object class.
• Object class is the super most class in java. If any class is not extending superclass, by default
will always extend object class.
• When subclass object is created, chaining constructors will be involved. The constructor of sub
class calls constructor of the superclass.
• The constructor of the super class in turn calls constructor of its super class. This is known as
chain of constructor.
• Java compiler makes an implicit call to the super class constructor using super() from subclass
constructor
• In super class, if default/ no argument constructor is not accessible, then the constructor should
be called explicitly using super statement along with argument(s) as expected from superclass .
• The Super statement should be always the first statement in the constructor
• Using super statement we can call any of the superclass constructors
• Whenever the java compiler makes a call to the super class, when super() is not mentioned, it
writes super() statement implicitly.
POLYMORPHISM
two types of polymorphism:
1. Method overloading – Compile time polymorphism
2. Method overriding - Runtime polymorphism

Method overloading – Compile time polymorphism.


• If a class has same name but different in parameters, it is known as Method overloading.
• If we have to perform one operation having same name of methods, to ensure readability of the
program.

Advantage:
1. Increases readability of the program.
2. Method overloading applies to both static and non static methods
3. Method can be overloaded in same class or subclass.

Ways to achieve method oevrloading:


Method overloading can be performed by changing:
1. Number of parameters
2. Datatype of parameters
3. Sequence of parameters
Interview question:
Can we overload main method?
Yes, but JVM choses/executes only method which accepts String array as an argument.

Method overriding – Runtime polymorphism


If the sublcass provides new implementation to the method already present in super class, it is called
as Method overriding.

Rules:
1. There should be inheritance or ‘IS A’ relationship
2. Method should be non-static
3. Method must have same name as in the superclass with same signature and in same order
4. Return type should also be same.

NOTE: Static methods are not overridden in the sub class but it is hidden.
Interview questions:

Can we override static methods?


No, because static method is bound with class whereas instance method is bound with object. Static
belongs to class area and instance belongs to heap area.

Can we override main method?


No, because it is a static method.

STATIC BINDING AND DYNAMIC BINDING


Connecting a method call to the method body is known as binding.
There are two types of binding
1. Static binding /early binding
2. Dynamic binding/late binding.

super keyword in java


The super keyword in java is a reference variable which is used to refer immediate parent class object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly which is
referred by super reference variable.

Usage of java super Keyword

1.super can be used to refer immediate parent class instance variable.

2.super can be used to invoke immediate parent class method.

3.super() can be used to invoke immediate parent class constructor.

class Animal
{

String color="white";
}
class Dog extends Animal
{
String color="black";
void printColor()
{
System.out.println(color); //prints color of Dog class
System.out.println(super.color); //prints color of Animal class
}
}
class TestSuper1
{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}
}

The super keyword can also be used to invoke parent class method. It should be used if subclass
contains the same method as parent class. In other words, it is used if method is overridden.

class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void eat()
{
System.out.println("eating bread...");
}
void bark()
{
System.out.println("barking...");
}
void work()
{
super.eat();
bark();
}
}
class TestSuper2
{
public static void main(String args[])
{
Dog d=new Dog();
d.work();
}
}

The super keyword can also be used to invoke the parent class constructor.

Class Animal{
Animal()
{
System.out.println("anima lis created");}
}
class Dog extends Animal
{
Dog()
{
super();
System.out.println("dog is created");
}
}
classTestSuper3
{
public static void main(String args[])
{
Dog d=new Dog();
}
}

FINAL VARIABLE
The final keyword in java is used to restrict the user. The java final keyword can be used in many
context. Final can be:

1.variable

2.method

3.class

It is a variable value which do not change during execution. We create it using the keyword ‘final’. The
value assignment should be done at the time of declaration only.

Final variables are usually named in CAPS

Ex: final float PI=3.14; Static final int NO_WHEELS=4;

Note: Uninitialized final variable is called blank final variable and this has to be initialized in static block.
The final keyword can be applied with the variables, a final variable that have no value it is called
blank final variable or uninitialized final variable.
It can be initialized in the constructor only. The blank final variable can be static also which will be
initialized in the static block only.
Class Demo8
{
Static final double PI=3.14; // constant value should be assigned in the same statement
public static void main(Strings…args)
{
final int NO_WHEELS;
NO_WHEELS=4; // can be done in same line or different line
System.out.println(PI);
System.out.println(NO_WHEELS);
NO_WHEELS=8; // will not work, cannot reassign value to a final variable
System.out.println(NO_WHEELS); // gives error
}
}

Interview Questions
1. Is final method inherited?
Yes, final method is inherited but you cannot override it.

2. What is blank or uninitialized final variable?


A final variable that is not initialized at the time of declaration is known as blank final variable.
If you want to create a variable that is initialized at the time of creating object and once initialized may
not be changed, it is useful. For example PAN CARD number of an employee.
It can be initialized only in constructor.

3. Can we initialize blank final variable?


Yes, but only in constructor.
4. What is final parameter?
If you declare any parameter as final, you cannot change the value of it.

5. Can we declare a constructor final?


No, because constructor is never inherited.

Arrays: Arrays are objects in java that stores multiple values of same type. Arrays can hold either
primitive or object references. But the array itself is an object even if the array is declared to hold
primitive elements
arraytype[] arrayName = new arraytype[size];
int arrayName[]; // here you shouldn’t mention the size
int array[] = {value 1, value 2, value 3}; or
int array[] = new int[]{value 1, value 2, value 3};
Examples:
a. int age[] = new int[3];
b. int[] marks = new int[4];
c. int scores[]; s
cores = new int[5];
d. int[] marks = {60, 50, 40, 90};

Note: If you are declaring array & constructing the array in some line you should declare the size Index
in an array starts with zero (0).
If the size is 3 means the indexes are 0, 1 and 2.
Array is fixed in size. Though you can create array object dynamically, once an array object is created,
we cannot increase or decrease the size
Empty array : array with zero (0) size.
Ex: int arr[] = new int[0];
Or int arr[] = {};
public class Demo12
{
public static void main(String args[])
{
int arr[] = new int[3];
arr[0]=10;
arr[1]=20;
arr[2] = 30;
for (int i=0; i<arr.lenght;i++)
{
System.out.println(arr[i]);
}
String arr1[] = new String [3];
arr[0]=”I”;
arr[1]=”Love”;
arr[2] = “java”;
for (String s: arr1) // for eachloop or enhanced for loop
{
System.out.println(s);
}
}
}
Arrays can be classified for our convenience as primitive array and non-primitive array. Ex: primitive
array Int arr[] = new int[5];
Non primitive array
Apple apples[] = new Apple[5];
Default values in array will be same as the default of the type declared.
i.e. if int arr[] then arr[0]. Will be zero(0) as default for int
if Apple apples[] then apples[0] will be null as default for Apple is null.
What is jagged array: it is an array of arrays where the size of each sub array can differ (Or) In
simple words, each row can contain different no of columns
Assigning & printing values in jagged array
public class Demo112
{
public static void main(String args[])
{
int arr[][] = {{3,5,7,9}, {4,2}, {5,7,8,6}, {6}};
(or) Int arr[][] = new int [][]{{3,5,7,9}, {4,2}, {5,7,8,6}, {6}};
for(int i=0; i<arr.length; i++)
{
for (int j=0; j<arr[i].length;j++)
{
System.out.printlnrint(arr[i][j]);
}
System.out.println();
}
System.out.println(“-----------------enhanced loop-----------------“);
for(int a[]:arr)
{
for(int i:a)
{
System.out.printlnrint(i);
}
System.out.println();
}
}
}

JAVA STRINGS
What is String?
In java, String is basically an object that represents sequence of character values.
Array of characters works similar to String.

Char ch[] = {'a','p','p','l','e'};


String s = new String(ch);

Java String provides number of methods to work with strings like compare(),
concat(),equals(),split(),length(),replace(),compareTo(),intern(),subString()

java.lang.String implements Serializable,Comparable and charSequence interfaces.


Java.lang.String class is used to create String object.

Two ways to create Strings


1. By String literals
2. By new keyword

By String literals:
String s = “Welcome”;
Each time you create a String literal, JVM checks the String already exists in constant pool first,
if the String already exists in th pool, reference of the pooled instance is returned else String is create
and placed in the pool.

String s1 = “Hello”;
String s2 = “Welcome”;
NOTE:
1. String objects are stored in special heap area called “String Constant Pool”.
To make memory usage more efficient and to avoid duplicate objects, this concept has been
implemented in Java.
By “new” keyword
String s = new String(“Welcome”);
In this case, JVM will create a new object in the non-pool heap.

String s1 = “Java”;
String s2 = new String(“Welcome”);
char ch[] = {'h','e','l','l','o'};
String s3 = new String(ch);

Methods available in String class

Sr.No. Method & Description


char charAt(int index)

1
Returns the character at the specified index.

int compareTo(Object o)

2
Compares this String to another Object.

int compareTo(String anotherString)

3
Compares two strings lexicographically.

int compareToIgnoreCase(String str)

4
Compares two strings lexicographically, ignoring case differences.

String concat(String str)

5
Concatenates the specified string to the end of this string.

boolean contentEquals(StringBuffer sb)

6 Returns true if and only if this String represents the same sequence of characters as the specified
StringBuffer.

static String copyValueOf(char[] data)


7
Returns a String that represents the character sequence in the array specified.

static String copyValueOf(char[] data, int offset, int count)

8
Returns a String that represents the character sequence in the array specified.

boolean endsWith(String suffix)

9
Tests if this string ends with the specified suffix.

boolean equals(Object anObject)

10
Compares this string to the specified object.

boolean equalsIgnoreCase(String anotherString)

11
Compares this String to another String, ignoring case considerations.

byte getBytes()

12 Encodes this String into a sequence of bytes using the platform's default charset, storing the result
into a new byte array.

byte[] getBytes(String charsetName)

13 Encodes this String into a sequence of bytes using the named charset, storing the result into a new
byte array.

void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)

14
Copies characters from this string into the destination character array.

int hashCode()

15
Returns a hash code for this string.

int indexOf(int ch)


16
Returns the index within this string of the first occurrence of the specified character.

int indexOf(int ch, int fromIndex)

17 Returns the index within this string of the first occurrence of the specified character, starting the
search at the specified index.

int indexOf(String str)

18
Returns the index within this string of the first occurrence of the specified substring.

int indexOf(String str, int fromIndex)

19 Returns the index within this string of the first occurrence of the specified substring, starting at the
specified index.

String intern()

20
Returns a canonical representation for the string object.

int lastIndexOf(int ch)

21
Returns the index within this string of the last occurrence of the specified character.

int lastIndexOf(int ch, int fromIndex)

22 Returns the index within this string of the last occurrence of the specified character, searching
backward starting at the specified index.

int lastIndexOf(String str)

23
Returns the index within this string of the rightmost occurrence of the specified substring.

int lastIndexOf(String str, int fromIndex)

24 Returns the index within this string of the last occurrence of the specified substring, searching
backward starting at the specified index.
int length()

25
Returns the length of this string.

boolean matches(String regex)

26
Tells whether or not this string matches the given regular expression.

boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int
len)
27
Tests if two string regions are equal.

boolean regionMatches(int toffset, String other, int ooffset, int len)

28
Tests if two string regions are equal.

String replace(char oldChar, char newChar)

29 Returns a new string resulting from replacing all occurrences of oldChar in this string with
newChar.

String replaceAll(String regex, String replacement

30 Replaces each substring of this string that matches the given regular expression with the given
replacement.

String replaceFirst(String regex, String replacement)

31 Replaces the first substring of this string that matches the given regular expression with the given
replacement.

String[] split(String regex)

32
Splits this string around matches of the given regular expression.

String[] split(String regex, int limit)


33
Splits this string around matches of the given regular expression.

boolean startsWith(String prefix)

34
Tests if this string starts with the specified prefix.

boolean startsWith(String prefix, int toffset)

35
Tests if this string starts with the specified prefix beginning a specified index.

CharSequence subSequence(int beginIndex, int endIndex)

36
Returns a new character sequence that is a subsequence of this sequence.

String substring(int beginIndex)

37
Returns a new string that is a substring of this string.

String substring(int beginIndex, int endIndex)

38
Returns a new string that is a substring of this string.

char[] toCharArray()

39
Converts this string to a new character array.

String toLowerCase()

40
Converts all of the characters in this String to lower case using the rules of the default locale.

String toLowerCase(Locale locale)

41
Converts all of the characters in this String to lower case using the rules of the given Locale.

String toString()

42
This object (which is already a string!) is itself returned.
String toUpperCase()

43
Converts all of the characters in this String to upper case using the rules of the default locale.

String toUpperCase(Locale locale)

44
Converts all of the characters in this String to upper case using the rules of the given Locale.

String trim()

45
Returns a copy of the string, with leading and trailing whitespace omitted.

static String valueOf(primitive data type x)

46
Returns the string representation of the passed data type argument.

String is Immutable
String value cannot be changed or modified. Once String is created, its data cannot be modified
or changed, instead a new String object is created.

String s1 = “Hello”;
s1.concat(“World”);
System.out.println(s1) => Hello //Because String is immutable

String s1 = “Hello”;
String s2 = s1.concat(“World”);
System.out.println(s2) => Hello World

Why are Strings immutable?


Since Strings are stored in constant pool, which doesn't allow duplicate values, if there are 5
reference variables that are pointing to a literal in constant pool, if one variable modifies the String
others are also affected. Hence it is immutable.

3 Ways to compare Strings


1. equals() method – Compares the content of the Strings
2. == - Compares reference(address) not values
3. compareTo() method – compares values lexicographically or based on alphabetic order.
a. Using equals() method
String s1 = “Hello”;
String s2 = “Hello”;
String s3 = new String(“Hello”);
String s4 = “Henry”;

System.out.println(s1.equals(s2); //true
System.out.println(s1.equals(s3); //true
System.out.println(s1.equals(s4); //false

b. == Operator

String s1 = “Hello”;
String s2 = “Hello”;
String s3 = new String(“Hello”);

System.out.println(s1 == s2) //true


System.out.println(s1 == s3) //false

c. compareTo
String s1 = “Hello”;
String s2 = “Hello”;
String s3 = new String(“Henry”);

System.out.println(s1.compareTo(s2)); //0
System.out.println(s1.compareTo(s3)); //Positiive integer (s1 > s3)
System.out.println(s3.compareTo(s1)); //Negative integer (s1 < s3)

String Concatenation
forms a new String that is a combination of multiple Strings
a. By + Operator
b. By concat operator

public class Demo


{
public static void main(String args[])
{
String s1 = “Hellollo”;
System.out.println (s1.lenght());
System.out.println (s1.concat(“Hello”));
System.out.println(s1);

String s2 = new String();


System.out.println(s2.lenght);
System.out.println(s2.isEmpty);

String s3 = new String(“”); // string


System.out.println(s3.lenght);
System.out.println(s3.isEmpty);

String s4 = new String(“ “); // space character is there in parenthesis


System.out.println(s3.lenght);
System.out.println(s3.isEmpty);

s2=s2.cancat(“Bangalore”);
System.out.println(s2.isEmpty);
System.out.println(s1.contains(“Dev”);

s1.equals(s2);
s1.equals(null);
s1.equals(“Hello”);
s1.equals(new String(“Hello”));
s1.equals(s1);
System.out.println(“Hello”.equals(“Hello”);
System.out.println(new String(“Hello”).equals(new String(“Hello”));
System.out.println(“”.equals(“”));

s1=”Hello”;
System.out.println(s1.equalsIgonrecase(“heLLO”);

s1 = “javaDeveloper”;
System.out.println(s1.indexof(‘D’);
System.out.println(s1.indexof(‘Deve’);
System.out.println(s1.indexof(‘Z’);
System.out.println(s1.indexof(‘e’);
System.out.println(s1.indexof(‘e’, 0);
System.out.println(s1.indexof(‘e’, 6);
System.out.println(s1.indexof(‘e’, 8);
System.out.println(s1.replace(“e”, “E”);
System.out.println(s1.replace(“e”, “java”); // replace all occurrences
System.out.println(s1.replace(“java”, “eg”); System.out.println(s1.replace(“ex”, “x”);
System.out.println(s1.replaceAll(“l”, “L”)); // we use this for regular expession
System.out.println(s1.charAt(0));

for(int i=0;i<s1.length(); i++);


{
System.out.println(s1.charAt(i));
}

//Printing s String in reverse order – VVVVVVVVVVV IMP


for(int i=s1.length(); i>=0; i--)
{
System.out.println(s1.charAt(i));
}
System.out.println(s1.charAt(0));
System.out.println(s1.charAt(s1.length()-1));

char ch = s1.charAt(1);
System.out.println(ch);
S1= “Jackand Jill”;
for (int i=0; i<s1.lenght();i++)
{
System.out.println(s1.charAt(i));
}
System.out.println(“--------”);
for (int i<s1.length()-1;i>=0;i--)
{
System.out.println(s1.charAt(i));
}
System.out.println(“--------”);

//Reversing a String– VVVVVVVVVVVVVVVVVVVV IMP (1st method)


String s3 = “”;
for (int i=s1.length()-1;i>0;i--)
{
s3 = s3 + s1.charAt(i);
}
System.out.println(s3);

System.out.println(s1.startswith(“java”));
System.out.println(s1.startswith(“dev”));
System.out.println(s1.endswith(“per”));
System.out.println(“DA”.compareTo(“DA”));
System.out.println(“DA”.compareTo(“GA”)); // when not same prints int value with the
difference of their Unicode values

System.out.println(s1.toUpperCase());
System.out.println(s1.toLowerCase());
System.out.println(“sum of 4 and 5 is ” + 4 + 5);
System.out.println(“sum of 4 and 5 is ” + (4 + 5));
System.out.println(4 + 5 + ”is sum of 4 and 5”);

//Reversing a String– VVVVVVVVVVVVVVVVVVVV IMP (2nd method)


Char chars[] = s1.toCharArray();
Strign s3 = “”;
for(int I = chars.length-1;i>=0;i--)
{
s3 = s3 + chars[i];
System.out.println(s3);
}

s3 = “JackandJill”;
Char arr[] = s3.tocharArray();
for (int i=0; i<arr.length;i++)
{
//prints char in array
System.out.println(arr[i] + “\t”); // print the Unicode value of the char
System.out.println((int)arr[i] + “\t”); // print the next char of the present char. It
means if A is there print B. if J is there print K.
System.out.println((char) (arr[i]+1) + “\t”); System.out.println((++arr[i]));
}
System.out.println(new String(“Hello”).length());
System.out.println(“Bangalore”.length());
String s4 = “ Hello “;
System.out.println(s4.length());
S4 = s4.trim();
System.out.println(s4.length());

//Alternate way
System.out.println(s4.trim().length());
S1 = “javaDeveloper’;
System.out.println(s1.subString(4));
System.out.println(s1.subString(4, s1.length());
// System.out.println(4, 11); here 4 is index (index numbering starts from 0) and 11 is the
position (position numbering starts from 1)

String str = “welcome subhankar to stackoverflow.com”;


System.out.println(str.subString(8, str.indexof(“ “, 8);
String s5 = “This is java class”);
String arr1[] = s5.split(“ “);
for(int i=arr1.length-1;i>=0;i--)
{
System.out.println(arr1[i] + “ “); } }
}
}
}

StringBuffer
• StringBuffer is a mutable class.
• It means we can update the value of object
• StringBuffer is a mutable class. It means we can update the value of object
• It is thread-safe which means multiple threads cannot access it simultaneously.

Creating StringBuffer Objects


a. StringBuffer() - creates an empty String with capacity of 16
b. StringBuffer(String s) – creates a new new StringBuffer of specified String.
c. StringBuffer(int capacity) – creates StringBuffer of specified index/capacity

package com.qspiders.stringdemo;
public class StringBufferDemo
{
public static void main(String[] args)
{
StringBuffer sb1=new StringBuffer();
StringBuffer sb2=new StringBuffer("Bangalore");
System.out.println(sb1 + " " + sb2);
System.out.println(sb1.reverse()); //updates the existing object
System.out.println(sb1); //same as above
System.out.println(sb1.reverse());

StringBuffer sb3=sb2.reverse() ;
System.out.println(sb1);
System.out.println(sb2);
System.out.println(sb3);
System.out.println(sb2==sb3); //true
sb1.setLength(0);

//sb1.delete(0, sb1.length()); //alternate


System.out.println(sb1.length());
System.out.println("--------");

StringBuffer sb4 = new StringBuffer();


System.out.println(sb4.length());
System.out.println("--------");
sb4.append("JavaDeveloper");
sb4.insert(4, "haha");
System.out.println(sb4); //JavahahaDeveloper
sb4.delete(4, 6);
System.out.println(sb4); //JavahaDeveloper
System.out.println(sb4.deleteCharAt(4)); //5th char 'h' is deleted
}
}

StringBuilder
StringBuilder class is also used to create mutable String. It is non-synchronized.

a. StringBuilder() - creates an empty String with capacity of 16


b. StringBuilder(String s) – creates a new new StringBuffer of specified String.
c. StringBuilder(int capacity) – creates StringBuffer of specified index/capacity

public class StringBuilderDemo


{
public static void main(String[] args)
{
StringBuilder sb5=new StringBuilder("Selenium");
System.out.println(sb5);
StringBuilder sbl;

System.out.println(sbl=sb5.insert(4, "Haha"));
System.out.println(sb5);
System.out.println("----");

System.out.println(sb5==sbl);
System.out.println(sb5.equals(sbl)); //true
System.out.println("--------"); //equals method not overridden

//compares address
System.out.println(sb5.reverse());
sb5.reverse();
System.out.println(sb5.delete(3, 7));

//String s=sb1//not possible since they are of diff class


//assiging StringBuffer content to String class
String s=sb1.toString(); //assiging String to StringBuffer class StringBuffer
sb6=new StringBuffer("Hello"); //1st way
sb6.append("Bangalore"); //2nd way
}
}

• String class of java.lang(package) is used to store the String object.


• A string object can be created either by using new keyword or direct assignment of the string
literal - Whenever a string object is created with help of string literal the objects are created in
the constant pool .
• The constant pool doesn’t allow duplicate objects.
• If the objects are created with new keyword then the objects will be created in non constant
pool. This pool allows duplicate objects
• If same object is being created in the constant pool the object will be created only once and all
the reference variables will be pointing to the same object.
• However in non constant pools the reference variable will be pointing to different object(new
object) of the same string.
• The string object is a immutable object since we cannot change the object's value
• In the String class toString() method and equals() method are overridden.
• The comparison of two String object is done based on value of the object.(First address is
compared if it returns false then value is compared)
• In order to compare wrt String values use equals() method
• From JDK1.5 onwards two additional classes called StringBuilder & StringBuffer class have been
introduced.
• This class can be used to create String object. Using any of these classes we can create object
with the help of new keyword.
• Both these Classes add an additional buffer of 16 characters to the String object
• The methods of StringBuffer classes give synchronized methods - reverse ,insert,delete
methods are available in StringBuilder & StringBuffer class

//Reversing a String– VVVVVVVVVVVVVVVVVVVV IMP (3rd method)


String s1 = “Hello”;
StringBuffer sb1 = new StringBuffer(s1);
sb1.return();
String s1 = sb1.toString();
//Reversing a String– VVVVVVVVVVVVVVVVVVVV IMP (4th method)
s1 = new StringBuffer(s1).reverse().toString();

Interview questions
1. Reverse a String
2. Reverse a String without using inbuilt functions (use 1st and 2nd )
3. Reverse a number. please see below programs

Reversing a number– VVVVVVVVVVVVVVVVVVVV IMP (1st method)


int i = 1234;
String s = Integer.toString();
StringBuffer sb1 = new StringBuffer(s);
sb1 = sb1.reverse90; Multiple lines program
s = sb1.toString();
i = Integer.parseInt(s);
i = Integer.parseInt(new StringBuffer(Integer.toString(i)).reverse().toString(); - single line
code
Reversing a number– VVVVVVVVVVVVVVVVVVVV IMP (2nd method)

public class reverseNumberwithoutfunction


{
public static void main(String[] args)
{
System.out.println(reverse(1234));
}

static int reverse (int I)


{
int reverse = 0;
while (i>0)
{
int remainder = i%10;
reverse = remainder + reverse*10;
i = i/10;
}
return reverse;
}
}
What is the difference b/w StringBuffer and StringBuilder?
• StringBuffer is synchronized StringBuilder is not synchronized.
• StringBuffer is thread-safe where-as StringBuilder is not thread-safe.
• StringBuffer is less-efficient than StringBuilder whereas StringBuilder is more efficient.

What is the difference b/w String and StringBuffer?


• Strings are immutable whereas StringBuffer are mutable
• Strings are slow and consumes more memory when you concat too many Strings because
everytime it creates new instance, whereas StringBuffer is fast and consumes less memory as
they are mutable.
• Strings overrides equals() method whereas StringBuffer doesn't override equals() method.

Exception Handling
• Exception is an event that gets triggered when JVM is not able to execute a statement.
• It can handled using try – catch block

package com.qspiders.exceptionDemo;
public class DemoExceptionDemo
{
public static void main(String[] args) ()
{
int i = 10;
int j;
try
{
System.out.println(“inside try block”);
j = i/10; System.out.println(“existing try block”);
}
catch (ArithmeticException e)
{
// e.printstackTrace(); // this is automatic method
System.out.println(“inside catch block”); }
}
}
In the below program JVM searches for the catch block which matches with the exception and executes
the corresponding catch block
package com.qspiders.pack1;
public class Demo115
{
public static void main(String[] args) ()
{
Int i=10;
Int j;
try
{
System.out.println(“inside try block”);
J=i/0;
// int k = Integer.parseInt(“test”);
}
catch (NumberFormatException exp)
{
System.out.println(“inside Number Format Exception catch block);
// exp.printStackTrace();
}
catch (ArithmeticException exp)
{
System.out.println(“Arithmetic Exception catch block);
// exp.printStackTrace();
}
System.out.println(“I = “ + i);
}
}
Above program also shows that for each statement that can generate exception, we need separate try
– catch block
// handling multiple statements that can generate exception use separate try-catch block Handling
multiple statements that can generate exception use separate try-catch block

package com.qspiders.pack1;
public class Demo
{
public static void main(String[] args) ()
{
int i=10;
int j;
try
{
System.out.println(“inside try block”);
j=i/0;
}
catch (ArithmeticException exp)
{
System.out.println(“Arithmetic Exception catch block); // exp.printStackTrace();
}
try
{
System.out.println(“inside Number Format Exception try block);
int k = Integer.parseInt(“Hundred”);
}
catch (NumberFormatException exp)
{
System.out.println(“inside Number Format Exception catch block);
// exp.printStackTrace();
}
System.out.println(“i = “ + i);
}
}

Alternately multiple statements can be handled using nested try-catch.


First statement should be inside the inner try long with corresponding catch block and the second
statement should be inside outer try.
package com.qspiders.pack1;
public class Demo115
{
public static void main(String[] args) ()
{
int i=10;
int j;
try
{
System.out.println(“inside try block”);
try
{
System.out.println(“inside inner try block);
j=i/0;
}
catch (ArithmeticException exp)
{
System.out.println(“Arithmetic Exception catch block);
// exp.printStackTrace();
}
int k = Integer.parseInt(“Hundred”);
}
catch (NumberFormatException exp)
{
System.out.println(“inside Number Format Exception catch block);
// exp.printStackTrace();
}
System.out.println(“i = “ + i);
}
}

‘finally’ block is used along with try catch mostly or can be used along with try alone (try – finally).
This block gets executed irrespective of a statement generating an exception or not We can have try-
catch or try-catch-finally or try-finally Following is the example
package com.qspiders.pack1;
public class Demo118
{
public static void main(String[] args) ()
{
int i = 10;
int j;
try
{
System.out.println(“inside try block”);
j=i/0;
System.out.println(“exiting try block”);
}
catch (ArithmeticException exp)
{
System.out.println(“inside catch block”);
}
finally // to mandatorily execute block of code
{
System.out.println(“inside finally block”);
}
System.out.println(“i= “ + i);
}
}

package com.qspiders.pack1;
public class Demo118
{
public static void main(String[] args) ()
{
System.out.println(“main method starts”);
System.out.println(test());
System.out.println(“main method ends”);
}
Static String test()
{
int i = 10;
int j;
try
{
System.out.println(“inside try block”);
j=i/0;
}
catch (AithmeticException exp)
{
System.out.println(“inside catch block”);
}
finally // to mandatorily execute block of code
{
System.out.println(“inside finally block”);
}
return “from outside block”;
}
}

• single try block can have multiple catch blocks


• If 2 exceptions class in catch block are subclass and super, first more specific and then super
class
public class MulitplecatchDemo
{
public static void main(String[] args)
{
String str="12.56";
Scanner sc=new Scanner(str);
int i=0;
try
{
i=sc.nextInt();
}
catch(InputMismatchException imexp)
{
System.out.println(imexp);
}
catch(NoSuchElementException nsexp)
{
System.out.println(nsexp);
}
catch(IllegalStateException iaexp)
{
System.out.println(iaexp); }
System.out.println(i);
}
}
when you want to catch an exception and throw another exception, you can chain the first exception
to the throwing exception or can return same exception
package com.qspiders.pack1;
public class ChainedExceptionDemo
{
public static void print()
{
try
{
String str[] = {“Hello”};
System.out.println(str);
}
catch (ArrayIndexOutofBoundException aiob)
{
throw new RuntimeException(aiob);
}
}
public static void main(String[] args) ()
{
try
{
print();
}
catch(RuntimeException re)
{
System.out.println(re.getclass());
System.out.println(re.getcause());
}
}
}

Package com.qspiders.smaple1;
Import java.util.Scanner;
Public class tryWithResourceDemo
{
public static void main(String[] args) ()
{
try(Scanner sc = new Scanner(System.in));
{
Int I = sc.nextint();
}
catch(exception e)
{
}
}
}
// we have resource inside the parenthesis of try block. Compiler will internally converts try with
resources to try finally block. If catch is present it will be returned Once work is done resources are
automatically closed. Don’t close it explicitly
package com.qspiders.pack1;
class Demo120
{
public static void main(String[] args) ()
{
System.out.println(“main starts”);
System.out.println(test());
System.out.println(“main ends”);
}
static String test()
{
int i=10;
int j;
try
{
j=i/2;
// put j=i/0 and try the program
return “pass”;
}
catch(Arithmetic Exception exp)
{
exp.printStackTrace();
return “fail”;
}
}
}
public class Demo
{
public static void main(String[] args) ()
{
System.out.println(“main starts”);
System.out.println(test());
System.out.println(“main ends”);
}

static String test()


{
int i=10;
int j;
try
{
j=i/2;
return “pass”;
}
catch(Arithmetic Exception exp)
{
exp.printStackTrace();
return “fail”;
}
finally
{
return “passfail”;
}
/*finally
{
System.out.println(“Hello Hello Dirty Fellow”);
} */
}
}

When we have return statement in finally block the o/p is – main starts passfail main ends
When we don’t have return statement and have print statement in finally block ( commented one in
above program) the o/p is – main starts Hello Hello Dirty Fellow pass main ends you can have return
statement in try and catch or in finally or only outside or in try-catch –finally (in all) or in catch-finally
or catch and outside.

If you have return in finally and outside finally block or in try-catch and outside catch block then it
becomes unreachable code and we shouldn’t write the code like this
Return statement in try-catch block
Exception Handling:
 An exception is an event triggered when jvm is not able to execute a statement Handling the event is
known as exception handling
 Whenever exception occurs jvm terminates the execution by throwing the exception message
 In order to complete the execution the exception should be handled by using try..catch block
 Always the try ..catch block should be written in sequence.
 try block alone is not allowed
 catch should take an argument of type exception
 try block should contain the statements which generates exception. Once an exception has occurred
jvm will go to catch block , remaining portion of the try block will never be executed
 In the catch body we can print the object or we can print the entire exception trace. After executing
the catch body the execution continues from the remaining program
 In between try-catch block no other executable statements are allowed

public class Demo122


{
public static void main(String[] args)
{
Demo122 r = new Demo122();
r.test1();
void test1()
{
Test2();
}
void test2()
{
Test3();
}
void test3()
{
Test4();
}
void test4()
{
int i=10/0;
}
}
} o/p – exception in thread “main” java.lang.ArtihmeticException:// by zero
-------------------------------------
Types of exceptions:
1. Checked exception
2. Unchecked exception

Note: throws keyword should be used only with checked exceptions


package com.qspiders.pack1;
public class Demo123
{
public static void main(String[] args) throws ClassNotFOUNDException
{
Class c1 = class.forName(“com.qspiders.pack1.Demo123”);
}
}

Checked exception: an exception which the compiler checks at the time of compilation is known as
checked exception. Checked exception can be handled using try-catch block or using throws keyword
along with the method through exception name. It should be written in the method name after the
closing parenthesis
Ex: returntype method name(paramlist) throws exception
1 and 3 are unchecked exceptions 2 is checked exception
Ex:
1. If we get IOException we can catch argument of same class or its super class exception
2. for NullPointerException use same method or RunTimeException or Exception or Throwable
What is an error?
Error is a subclass of Throwable class that indicates abnormal conditions which can cause
serious problems. It should not be handled.
Ex: stackoverflow error, when we use method recursion

Imp:
• Throwable is the base class of all exception classes.
• It is super most class of all exception classes

Creating your own exception


package com.qspiders.exceptionDemo;
import java.util.scanner;
class InvalidAgeException extends RuntimeException
{
InvalidAgeException(String str)
{
System.out.println(str);
}
}

public class Demo124


{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println(“Enter your age”);
int age = sc.nectInt();
try
{
if (Age>=60 || age<=0)
{
// System.out.println(“Invalid Age: please enter age b/n 1-60”)
throw new InvalidAgeException(“Invalid Age: please enter age b/n 1-60”);
}
}
catch (InvalidAgeException iae)
{
System.out.println(“Age Entered is” + age);
}
}
}

If we write our own exception class put it under any class RunTimeException or Exception. Then it
becomes checked exception or unchecked exception based on the superclass the user class extends
Exception in Java are classified into 2 types
1.Checked Exception
2. Unchecked Exception
Checked Exception:
• An Exception where the compiler can check at the time of compilation is known as checked
Exception
• Checked Exception should be handled in order to compile the program successfully.
• Checked Exception can be handled in 2 ways
1)Surrounding try-catch block
2)By using throws declaration statement

The throws declaration should be done in the method signature, the throws keyword should be used
only for checked exceptions.
Unchecked Exception: Exceptions which are not been able to be identified by the compiler at the time
of compilation is known as unchecked exceptions.
throws keyword cannot be used for unchecked exception and it should be handled only through
try,catch block.
• throw keyword is used to generate or throw an exception(existing exception class or user
defined exception) in the program.
• We can develop our own exception class by inheriting one of exception classes.

COLLECTIONS API
Collections in java is a framework that provides an architecture to store and manipulate the group of
obejcts.

Operations: insertion,deletion,manipulation,searching, sorting.

Java collections has provided many interfaces:


List, Set, Queue, Dequeue and classes like ArrayList, LinkedList, PriorityQueue, HashSet,
LinkedHashSet,TreeSet etc.

What is Framework?
Set of guidelines that provides ready-made architecture.

Methods available in Collection interface:


• add()
• addAll()
• remove()
• removeAll()
• size()
• clear()
• contains()
• isEmpty()

Iterator interface
It works like a loop statements which helps to iterate the elements in forward direction only.

Methods in Iterator
• hasNext()
• next()
• remove()
ARRAYLIST
Java ArrayList class uses dynamic array for sorting elements.

It inherits AbstractList class and List interface.


Features:
• Allows duplicate elements
• Allows null values
• Maintains insertion order
• Non-Synchronized
• Allows random access as it works based on indexing
• Manipulation is slow as a lot of shifting needs to be done if any element is removed from
ArrayList.

Syntax:
ArrayList al = new ArrayList();
ArrayList<String> al = new ArrayList<String>(); //generic way of creating

Two ways to iterate ArrayList.


For-each loop
Iterator

import java.util.ArrayList;
import java.util.Iterator;

public class ArrayListDemo


{
public static void main(String[] args)
{
ArrayList<String> al = new ArrayList<String>();
al.add("Apple");
al.add("Mango");
al.add("Orange");
al.add("Apple");
al.add("Grapes");
al.add("Pear");

Iterator<String> iter = al.iterator();


while(iter.hasNext())
{
System.out.println(iter.next());
}
}
}

Iterating ArrayList using for-each Loop

public class ArrayListDemo


{
public static void main(String[] args)
{
ArrayList<String> al = new ArrayList<String>();
al.add("Apple");
al.add("Mango");
al.add("Orange");
al.add("Apple");
al.add("Grapes");
al.add("Pear");

for(String fruits:al)
{
System.out.println(fruits);
}
}
}

User-Defined Objects in ArrayList

import java.util.ArrayList;
import java.util.Iterator;

public class Student


{
int roll;
String name;
String college;
Student(int r, String s,String c)
{
roll = r;
name = s;
college = c;
}
public static void main(String[] args)
{
Student s1 = new Student(1, "Steve","Oxford");
Student s2 = new Student(1, "Philip","Cambridge");
ArrayList<Student> al = new ArrayList<Student>();
al.add(s1);
al.add(s2);
Iterator<Student> iter = al.iterator();
while(iter.hasNext())
{
Student st = iter.next();
System.out.println(st.roll +" "+ st.name +" " +st.college);
}
}
}

Other methods:
• add()
• remove()
• addAll()
• removeAll()
• retainAll()
• clone()
• toArray()

Constructors of Java ArrayList


ArrayList()
ArrayList(Collection c)
ArrayList(int capacity)

LINKEDLIST
Java LinkedList used doubly linked list concept to store elements.

It inherits AbstractList class and implements List and Deque interfaces.


• Allows duplicate elements
• Maintains insertion order
• Non-Synchronized
• Allows null values
• Manipulation is fast as no arrangements/shifting is to be done
• It can be used as list, stack or queue

Constructors in LinkedList

LinkedList()
LinkedList(Collection c)
LinkedList(int capacity)

import java.util.LinkedList;
public class ArrayListDemo
{
public static void main(String[] args)
{
LinkedList<String> al = new LinkedList<String>();
al.add("Apple");
al.add("Mango");
al.add("Orange");
al.add("Apple");
al.add("Grapes");
al.add("Pear");

for(String fruits:al)
{
System.out.println(fruits);
}
}
}

Difference b/w ArrayList and LinkedList

ListInterface

It is a sub-interface of collection. It contains methods to insert and delete elements.

Methods
• add(index,object)
• addAll(index,collection)
• get(index)
• set(index,object)
• remove(index)

ListIterator interface
ListIterator interface extends Iterator.
It is used to iterate/traverse the elements in list in forward/backward direction

Methods
• hasNext()
• next()
• hasPrevious()
• previous()

SET
Set will not accept duplicate values.
Values are stored in the form of index instead stores in the form of hashcode
Set will accept null values.

3 Different classes under Set


1. HashSet
2. LinkedHashSet
3. TreeSet

HashSet
Used to create collection that uses hashtable for storage
Inherits AbstractClass and implements Set interface

Constructors of HashSet
HashSet()
HashSet(Collection c)
HashSet(int capacity)

import java.util.HashSet;
public class HashSetDemo
{
public static void main(String[] args)
{
HashSet<String> set = new HashSet<String>();
set.add("Mercury");
set.add("Helium");
set.add("Sulphur");
set.add("Nitrogen");
set.add("Nitrogen");
for(String gas:set)
{
System.out.println(gas);
}
}
}

NOTE: If duplicate values are inserted into Set(HashSet, TreeSet or LinkedHashSet), no errors will be
displayed, but the value will be considered only once.

Methods in HashSet
• clear()
• contains(object o)
• add(Object o)
• isEmpty()
• remove(Object o)
• clone()
• iterator()
• size()

LinkedHashSet
It is a hashtable and linked list implementation of Set interface.
Inherits HashSet class and implements Set interface.
Allows only unique values
Allows all set operations and permits null
Maintains insertion order.

Constructors of LinkedHashSet

LinkedHashSet()
LinkedHashSet(Collection c)
LinkedHashSet(int capacity)

import java.util.LinkedHashSet;

public class LinkedHashSetDemo


{
public static void main(String[] args)
{
LinkedHashSet<String> set = new LinkedHashSet<String>();
set.add("Daisy");
set.add("Rose");
set.add("Jasmine");
set.add(null);
set.add("Lilly");
set.add("Jasmine");
for(String flowers:set)
{
System.out.println(flowers);
}
}
}
TreeSet
Uses tree structure for storage
Inherits AbstractClass and implements NavigableSet interface.
Objects are stored in ascending order(sorted)
Allows distinct values
Doesn't allow null values.
maintains ascending order
Access and retrieval times are faster

Constructors of TreeSet

TreeSet()
TreeSet(Collection c)
TreeSet(Comparator comp) – constructs empty TreeSet that will be sorted according to given
comparator
TreeSet(SortedSet ss) – constructs TreeSet that contains elements of given sortedSet.

import java.util.TreeSet;

public class TreeSetDemo


{
public static void main(String[] args)
{
TreeSet<String> set = new TreeSet<String>();
set.add("Daisy");
set.add("Rose");
set.add("Jasmine");
set.add("Lilly");
set.add("Jasmine");
for(String flowers:set)
{
System.out.println(flowers);
}
}
}

Methods in TreeSet
• addAll(Collection c)
• contains(object o)
• isEmpty()
• remove(Object o)
• add(Object o)
• clear()
• clone()
• first()
• last()
• size() etc...

MAP INTERFACE
• Map contains values based on key and value pairs.
• Each key and value is known as Entry
• Map contains only unique keys
• Useful to search, update or delete elements based on key.

Map.Entry Methods
getKey() - returns key(Object)
getValue() - returns value(object)

Other Methods
• put(object key, Object value)
• putAll(Map m)
• remove(Object key)
• get(Object key)
• containsKey(Object key)
• keySet()
• entrySet()

HashMap
Implements Map interface and inherits AbstractMap class.
HashMap contains values based on key
Contains only unique elements
Allows only one null key and multiple null values
Maintains no order
HashMap Parameters
k: type of keys maintained by map
v : type of mapped values
Constructors of HashMap
HashMap()
HashMap(Map m)
HashMap(int capacity)

import java.util.HashMap;
import java.util.Map;

public class ArrayListDemo


{
public static void main(String[] args)
{
HashMap<Integer, String> omap = new HashMap<Integer,String>();
omap.put(100, "Steve");
omap.put(200, "Philip");
omap.put(300, "Stephen");

for(Map.Entry<Integer, String> m : omap.entrySet())


{
System.out.println(m.getKey() +" : "+m.getValue());
}

}
}

Methods of HashMap
• clear()
• contains(Object Key)
• containsValue(Object value)
• isEmpty()
• clone()
• entrySet()
• keySet()
• put(Object key, Object value)
• size()
• Collection values – returns a collection view of values

LinkedHashMap
Contains values based on key
contains only unique elements
Allows one null key and multiple null values
Same as HashMap but maintains insertion order

Methods of LinkedHashMap
• get(Object key)
• clear()
• containsKey(Object Key)

TreeMap

Implemets Map interface by using a tree.


Provides efficient means of storing key/value pairs in sorted order
Contains values based on key.
Implements NavigableMap interface and extends Abstractmap
Cannot have null key but can have multiple null values
Same as HashMap but maintains sorted ascending order.

Methods of TreeMap

• containsKey(Object key)
• conatinsValue(Object value)
• firstKey()
• lastKey()
• remove(object Key)
• putAll(map m)
• entrySet()
• size()
• Collection values()

COLLECTIONS Class
Collections is a class which inherits Object Class.
Uses static methods to operate on Collections.
Throws NullPointerException if collections or class objects provided yo them are null.
Methods of Collection class
• addAll(Collections c)
• binarySearch()
• reverse()
• max()
• min()
• sort() - We can sort elements of Strings, Wrapper classes such as Integer, Double, Float and
also User-defined classes.

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;

public class ArrayListDemo


{
public static void main(String[] args)
{
ArrayList<String> al = new ArrayList<String>();
al.add("rose");
al.add("Lilly");
al.add("Jasmine");
al.add("Lotus");

Collections.sort(al);
Iterator< String> iter = al.iterator();
while(iter.hasNext())
{
System.out.println(iter.next());
}
}
}

Comparable Interface
Comparable Interface is used to order the objects of user-defined classes.
Interface is found in java.lang package and contains only one method compareTo(Object o)

We can sort the elements of


• String Objects
• Wrapper class objects
• User-Defined class objects.

Note: String and wrapper classes implements Comparable interface by default. So if you store objects
of String or wrapper classes in list, set or map, it will be comparable by default.

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;

class Student implements Comparable


{
int roll;
String name;
int age;

Student(int r, String n, int a)


{
roll = r;
name = n;
age = a;
}

public String toString()


{
return this.roll + " " + this.name +
" " + this.age;
}

public int compareTo(Object o)


{
Student s1 = (Student)o;
return this.age - s1.age;
}
}
public class Demo
{
public static void main(String[] args)
{
ArrayList<Student> list = new ArrayList<Student>();
list.add(new Student(30,"Philip",15));
list.add( new Student(1,"Steve",20));
list.add(new Student(12,"Steve",10));

Collections.sort(list);
Iterator iter = list.iterator();
{
while(iter.hasNext())
{
System.out.println(iter.next());
}
}
}
}

Comparator Interface
This is also used to order objects of user-defined class.
Interface is found in java.util package and contains 2 methods.

• compare(Object obj1, Object obj2)


• equals(Object element)

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;

class Student
{
int roll;
String name;
int age;

Student(int r, String n, int a)


{
roll = r;
name = n;
age = a;
}

public String toString()


{
return this.roll + " " + this.name +
" " + this.age;
}
}
class AgeComparator implements Comparator
{

@Override
public int compare(Object o1, Object o2)
{
Student s1 = (Student) o1;
Student s2 = (Student) o1;
if(s1.age == s2.age)
return 0;
else if(s1.age > s2.age)
return 1;
else
return 0;
}
}

public class Demo


{
public static void main(String[] args)
{
Student s1 = new Student(1,"Steve",18);
Student s2 = new Student(2,"Steve",17);
Student s3 = new Student(3,"Philip",16);
ArrayList<Student> list = new ArrayList<Student>();
list.add(s1);
list.add(s2);
list.add(s3);

Collections.sort(list, new AgeComparator());


Iterator iter = list.iterator();
{
while(iter.hasNext())
{
System.out.println(iter.next());
}
}
}
}

Difference between Comparable and Comparator Interfaces

JAVA I/ O(Input/Output)

Java I/o classes is used to process the input and produce output.
Uses concept of Stream classes
present in java.io package.

Stream: Sequence of data


In Java, there are 3 streams created automatically.
• System.out
• System.in
• System.err

2 types of Streams are


• Output Stream
• Input Stream.

OutputStream: Used to print data on destination, array or file.

Methods
• write(int) throws IOException
• write(byte[]) throws IOException
• flush() throws IOException
• close() throws IOException

InputStream
Used to read data from source, file or array.

Methods
• int read() throws IOException
• void close() throws IOException

SUMMARY

• Java provides IO package to write a program which handles files as well as directory of file
system.
• File class is used for basic operations like
1. create
2. delete
3. check existence
4. get path
5. check permissions

Classes available
• File
• FileReader
• FileWriter
• FileInputStream
• FileOutputStream
File Class
Provides basic operations.

import java.io.File;
public class FileDemo {

public static void main(String[] args)


{
System.out.println("Programs starts");
File f1 = new File("Sample");
System.out.println(f1.mkdir());
System.out.println(f1.getAbsolutePath());
System.out.println(f1.isDirectory());
System.out.println(f1.exists());
System.out.println(f1.delete());
System.out.println(f1.exists());
System.out.println("Program ends");
}
}

FILE HANDLING

import java.io.File;
import java.io.IOException;
public class FileDemo {

public static void main(String[] args)


{
try
{
File f1 = new File("D:\\Demo.txt");
System.out.println(f1.createNewFile());
System.out.println(f1.getAbsolutePath());
System.out.println(f1.isFile());
System.out.println(f1.exists());
System.out.println(f1.canWrite());
System.out.println("Program ends");
}
catch (IOException e)
{
e.printStackTrace();
}
}
}

FILEWRITER Class

Used to write character-oriented data to a file.

CONSTRUCTORS
• FileWriter(String File)
• FileWriter(File file)

METHODS
• void write(String text)
• void write(char c)
• void write(char[] c)
• void flush()
• void close()

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class FileDemo {

public static void main(String[] args)


{
File f1 = new File("D:\\Demo.txt");
FileWriter fwrite = null;
try
{
fwrite = new FileWriter(f1);
fwrite.write("Welcome to Java programming\r\n");
fwrite.write("Hello World\r\n");
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
fwrite.flush();
fwrite.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
System.out.println("Total char : "+f1.length());
}
}

FILEREADER Class
Used to read data from file. It returns data in byte format.

CONSTRUCTORS
• FileReader(String file)
• FileReader(File file)

METHODS
• int read()
• void close()

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class FileDemo {

public static void main(String[] args)


{
File f1 = new File("D:\\Demo.txt");
FileReader fread = null;
try
{
fread = new FileReader(f1);
char data[] = new char[(int)f1.length()];
fread.read(data);
String s1 = new String(data);
System.out.println(s1);
fread.close();
}catch(IOException e)
{
e.printStackTrace();
}
}
}

//Program2
import java.io.FileReader;
import java.io.IOException;
public class FileDemo {

public static void main(String[] args) throws IOException


{
FileReader fr = new FileReader("D:\\Demo.txt");
int i;
while((i=fr.read())!=-1)
{
System.out.println((char)i);
}
fr.close();

}
}

FILEOUTPUTSTREAM Class

• Used for writing data to a file.


• Used to write primitive types.
• Allows to write byte-oriented as well as character-oriented data.
METHODS

void finalize()
write(byte[] arr)
write(byte[] arr, int off, int len)
write(int b)
close()

import java.io.FileOutputStream;
import java.io.IOException;
public class FileDemo {

public static void main(String[] args) throws IOException


{
try
{
FileOutputStream fout = new FileOutputStream("D:\\Sample.txt");
fout.write(65);;
System.out.println("Success");
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

FILEINPUTSTREAM Class

• Obtains uinput bytes from a file.


• Allows to read byte-oriented as well as character oriented stream.
• Uses FileReader class object.
• Byte-oriented: image, data,audio, video etc.

METHODS
• available() - returns int
• read() - returns int
• read(byte[] b)
• int read(byte[] b, int off, int len)
• protected void finalize()
• void close()

import java.io.FileInputStream;
import java.io.IOException;
public class FileDemo {

public static void main(String[] args) throws IOException


{
try
{
FileInputStream fout = new FileInputStream("D:\\Sample.txt");
int ch = fout.read();
System.out.println(ch);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

SERIALIZATION
Process of writing java object into a file is called as Serialization. To serialize an object of a class
the object should be of serializable type, means the class should implement Serializable interface.

The objective/aim of serialization is to store the object permanently.

Serializable interface is a marker interface which doesn't have abstract methods.

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;

class Student implements Serializable


{
int roll;
String name;

Student(int r, String n)
{
roll = r;
name = n;
}
}

public class FileDemo {

public static void main(String[] args) throws IOException


{
ObjectOutputStream bout = null;
FileOutputStream fout = null;
try
{
fout = new FileOutputStream("D:\\Sample1.txt");
bout = new ObjectOutputStream(fout);
Student s1 = new Student(1, "Steve");
bout.writeObject(s1);
}
catch(Exception e)
{
e.printStackTrace();
}

finally
{
bout.flush();
bout.close();
fout.close();
}
}
}
DESERIALIZATION
Process of reading java objects from a file is called as deserialization.

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;

class Student implements Serializable


{
int roll;
String name;

Student(int r, String n)
{
roll = r;
name = n;
}

void display()
{
System.out.println(roll);
System.out.println(name);
}
}

public class FileDemo {

public static void main(String[] args) throws IOException


{
ObjectInputStream bin = null;
FileInputStream fin = null;
try
{
fin = new FileInputStream("D:\\Sample1.txt");
bin = new ObjectInputStream(fin);
Student s1 = (Student) bin.readObject();
s1.display();
}
catch(Exception e)
{
e.printStackTrace();
}

finally
{
bin.close();
fin.close();
}
}
}

NOTE: In ObjectInputStream, readObject() reads the object from file. When it reads from file, it will be
in object type, that object should be down-casted to respective subclass object.

Wrapper classes
To convert primitive data type into an object, we use
Byte, Short, Integer, Long, Float, Double, Character, Boolean.
Since they wrap around primitive it is called wrapper classes
• Converting primitive data type into an object is called as auto boxing (compiler does it)

• Converting an object (which is converted from auto boxing) to primitive type is called as
unboxing. (developer does it)

• In both the cases we use wrapper class.


• For every primitive type, respective wrapper class is given by JDK.
• Every wrapper class will have overloaded constructor (except character class).
• They do not use default constructor in wrapper class.

Note:
1. Generally whenever a reference variable is printed, the address of the object will be printed. The
address is usually represented with fully qualified class name – fullyqualifiedclassname@hexadecimal
address of the object
2. Whenever a reference variable of any wrapper class is used or printed then it prints the primitive
data of the wrapper class instead of address. Because in every wrapper class toString() method of the
object class has been overridden to display or return the primitive data instead of address
public lass Demo91
{
public static void main(String[] args)
{
int I = 10;
System.out.println(i);
Integer intobj1 = new Integer(i); // boxing operation
System.out.println(intobj1);
Integer intobj2 = new Integer(100); // boxing operation
System.out.println(intobj2);
Integer intobj3 = new Integer(“200”); // boxing operation
System.out.println(intobj3);
Integer intobj4 = 300;
System.out.println(intobj4);
}
}
o/p – 10 10 100 200 300
// Integer intobj2 = 100; (this is correct)
// Integer intobj2 = i; (this is correct)

Wrapper class:

 In java.lang

 Two constructors for each wrapper class except character class (only one constructor)

 toString(), equals and hashCode() method is overridden


Every number related wrapper class inherit from super class Number (Number class is on abstract
class).
It is inherited from object class.
The Number class methods are overridden in every wrapper class which deals with numbers
public class Demo92
{
PSVM()
{
int i=100;
Integer intobj = new Integer(i); // boxing operation
SOP(intobj);
Int j = intobj.intvalue();// unboxing operation
SOP(j);
}
}

Boxing operation: by passing primitive value to wrapper class constructor of respective type Unboxing:
by calling non static method of boxed variable
public class Demo93
{
public static void main(String[] args)
{
int i=100;
Integer intObj=new Integer(i); // boxing operation
System.out.println(intObj);
int j=intObj.intValue(); //unboxing operation
System.out.println(j);
double d=intObj.doubleValue();//unboxing and autowidening
System.out.println(d);

//1st way
Double dd=new Double(d);//boxing
System.out.println(dd);

//2nd way
Double dd1=new Double("12.56");//boxing
System.out.println(dd1);

//3rd way
Double dd1=d;//boxing
System.out.println(dd1);
System.out.println("unboxing");
int i1=dd1.intValue(); //unboxing and narrowing
System.out.println(i1);
System.out.println("unboxing and explicit narrowing");

int i2=(int)dd1.doubleValue();
System.out.println(i2);
byte b=123;
Long ll=new Long(i);//i autowidening
Long ll1=new Long(b);//b autowidening
System.out.println(ll);
System.out.println(ll1);
long l=100;
Byte bb=new Byte((byte)l);
System.out.println(bb);
System.out.println("converting object to String");
String s1=ll.toString();
System.out.println(s1);
System.out.println("----");

Double dd=new Double(100);


String s=dd.toString();//object to String
Double.toString(10.22);//primitive to String

Long.toString(100l);//ditto
Byte.toString((byte)100);

//String s2=ll; cannot convert from Long to // String, assigning ll address to s2


//Add two string containing numbers and put in another string
String s11="123";
String s22="456";
String s33=Integer.toString(Integer.parseInt(s11)+Integer.parseInt(s22));
System.out.println(s33);

Integer ii=new Integer(123);


Integer ii2=ii;//assigning the address
System.out.println(ii==ii2);//true
System.out.println(ii2);

Integer ii3=Integer.valueOf(ii); //returning an new Integer object


System.out.println(ii==ii3);//false
}
}

INTERVIEW QUESTIONS
1. how do you convert int to a String
int i = 10;
System.out.println(Integer.toString(i));

2. how do you convert String to int


String s = "10";
System.out.println(Integer.parseInt(s));
3. how do you convert object to a String
String s1 = Obj.toString();

4. how do you convert String to char


public static void main(String[] args)
{
String s = "Hello";

for(int i =0;i<s.length();i++)
{
char ch=s.charAt(i);
System.out.println(ch);
}
}

5. how do you convert char to String


public static void main(String[] args)
{
char ch[] ={ 'A','p','p','l','e'};
String s = new String(ch);
}

6. Reverse a String
public static void main(String[] args)
{
String s1 = "Hello" ;
StringBuffer sb1 = new StringBuffer(s1);
sb1.reverse();
String s2 = sb1.toString();
System.out.println(s2);

}
7. Reverse a String without using inbuilt functions (use 1st and 2nd )
public static void main(String[] args)
{
String s1 = "Hello";
String s3 = "";
for (int i=s1.length()-1;i>=0;i--)
s3 = s3 + s1.charAt(i);
System.out.println(s3);
}

8. Reverse a number. please see below programs


public static void main(String[] args)
{
int i = 1234;
String s = Integer.toString(i);
StringBuffer sb1 = new StringBuffer(s);
sb1 = sb1.reverse(); //Multiple lines program
s = sb1.toString();
i = Integer.parseInt(s);
System.out.println(i);
}

9. what are the difference b/w static and instance members?Mention 3 difference
• Static members are bound to class whereas instance members are bound to objects
• Static members can be accessed using both classname and objects whereas instance members
can be invoked only using objects.
• Static members maintains only one copy throughout the class, whereas instance members
maintains one copy for every objects
• Static members are the members which are declared using static keyword, whereas instance
members are the global variables which are declared outside the method and within a class.
• Static variables can be directly accessed within a static method or block without the help of an
object, whereas instance variables always needs an object to be accessed.

10. what variables are called as fields?


Instance variables

11. what variables should be compulsorily initialized?


Instance variables

12. what variables will be initialized to default values if not initialized?


Primitive variables/variables of primitive datatype.

13. what is constant in java?


Final members are called as constant members. Members can be variables, methods or classes.
If variables are declared final, value of the variable cannot be changed.
If methods are declared as final, they cannot be overridden.
If class is declared as final, it cannot be inherited.

14. what is blank final and should it be initialized, if so, where?


A final variable which is not initialized is known as blank final variable.
It should be initialized only in static block.

15. WAP to print o/p should be print:"World's End"


public static void main(String[] args)
{
System.out.println("\"World's end\"");
}
16. WAP to print o/p \n
public static void main(String[] args)
{
System.out.println("\\n");
}

17. what is the o/p of


System.out.println('A'+'B');
Ans: 131
System.out.println('A'+ "B");
Ans : AB
System.out.println('A'+ 100);
Ans: 165
System.out.println("A"+ 100);
Ans: A100

18. what happens ?


int x=5;
int y = 5;
boolean res=x!=y;

a)System.out.println('res');
Ans : Compilation error - Invalid character constant

b)System.out.println(res);
Ans: false
c)System.out.println("res");
Ans: res

d)System.out.println(TRUE);
Ans: Compilation error

e)System.out.println(true);
true

19. what is ==? Explain


◦ == is the relational operator which is used to check whether 2 variables are equal or not.
◦ When it is used with primitive datatypes like int, double, float, long it will check the value of
the variable
Ex: int a = 5;
int b = 5;
if(a == b)
System.out.println(“a and b are equal”);
else
System.out.println(“a and b are not equal”);
◦ If it is used with Strings, then it is used to compare the reference or address of 2 Strings.
(String constant pool concept comes into picture)
Ex: String s = “Hello”;
String s1 = “Hello”;
System.out.println(s1 == s2); //prints true

20. what happens?


Orange o1=new Orange();
Orange o2=new Orange();
a) System.out.println(o2);
b) System.out.println(o1==o2);
c) System.out.println(o1!=o2);
d) System.out.println(o1>=o2);

21. WAP using nested conditional operator.


Take marks as input .classify as fail(0-<50),pass(50-60),fc(61-74) distinction(75-
100)and invalid
public class NestedIfStatement {

public static void main(String[] args)


{
int marks = 95;
if(marks>=75 && marks <=100 )
{
System.out.println("Distinction");
}
else if(marks >=75 && marks <=100)
{
System.out.println("First class");
}
else if(marks <=50 && marks <35)
{
System.out.println("Second class");
}
else ( marks <=35 && marks <0)
{
System.out.println("Fail");
}
else
{
System.out.println("Invalid");
}
}
}
22. what is difference b/w JDK,JRE and JVM?
JVM is the Java virtual Machine. It is an abstract machine, that provides runtime environment in
which byte code can be executed.
JVM performs task such as: Loading code, verifying code, executing code, provides runtime
environment.

JRE - Java runtime Environment is the implementation of JVM. It physically exists. It contains
Set of libraries+other files that JVM uses for execution.

JDK is nothing but Java Development Kit. It physically exists. It contains JRE+ development
tools like javac, java etc.

23. .what is a variable?


These are properties of the class or object which we are going to create
Ex: If we are creating a class called car, then they have properties like model no, Colour, seats
etc.
In simpler way it can said as variables which holds values

“Variables are also called as fields”


There are 3 different type of variables:
Local – which belong to a method or a block
Instance variables – which belongs to objects / they are also called as global variables
Static variables – which belong to class.

24. what is a method? What are the types of methods


Block of code written to accomplish a particular task or Behavior or the actions that can be
performed by an object or a class
Syntax:
returntype methodname(ParameterList)
{
//method body
}
Method types
• Method without returntype and without parameters
void method1()
{
//body
}
• Method without returntype and with parameters
void method1(int a , int b)
{
//body
}
• Method with returntype and without parameters
int method1()
{
//body
}
• Method with returntype and with parameters
int method1(int a , int b)
{
//body
}
25. what is difference b/w static and non static members?
• static members are one per class but non-static members are one per instance.
• static members are accessed by their class name which encapsulates them, but non-
static members are accessed by object reference.

• static members can't use non-static methods without instantiating an objet, but non-
static members can use static members directly.
• static constructor is used to initialize static fields, but for non-static fields normal
instance constructor is used.

26. what is package?


package is a grouping (or folder structure) of related classes/ interfaces/ enumerations
or annotation types providing access protection and name space management
This helps in
• Grouping of related types like classes and/ or interfaces
• Avoiding name conflicts with classes created in same or other projects in the same
company
• You can allow types within the package to have unrestricted access to one another. yet still
restrict access for types outside the package

27. what are the access specifiers?


The access specifies in java indicates visibility of the members of the class. Java supports following 4
specifier levels.
◦ You can apply the access specifiers to classes, variables, methods & constructors
◦ Package declaration should be the first statement.
◦ If you are importing any class from another package, then this should be the second -
statement.
◦ You can import as many classes as you want from any other packages
◦ Third should be class statement
◦ Different access Specifiers are
1. Private
2. Protected
3. Public

28. what are the non access specifiers?


Java provides a number of non-access modifiers to achieve many other
functionalities.
◦ The static modifier for creating class methods and variables.
◦ The final modifier for finalizing the implementations of classes, methods, and variables.
◦ The abstract modifier for creating abstract classes and methods.
29. what is abstraction?
Abstraction is the process of hiding the implementation and showing only the functionalities.
There are two ways to achieve abstraction
1. Abstract classes – 0-100% abstraction
2. Interfaces – 100% abstraction

30. what is difference b/w abstract class and interface?

◦ Abstract classes can have constants, members, abstract methods and concrete
methods, whereas interfaces can only have constants and abstract methods.

◦ Methods and members of an abstract class can be defined with any visibility, whereas all
methods of an interface must be defined as public (they are defined public by default).

◦ When inheriting an abstract class, a concrete child class must define the abstract
methods, whereas an abstract class can extend another abstract class and abstract
methods from the parent class don't have to be defined.

◦ Similarly, an interface extending another interface is not responsible for implementing


methods from the parent interface. This is because interfaces cannot define any
implementation.

◦ A child class can only extend a single class (abstract or concrete), whereas an interface
can extend or a class can implement multiple other interfaces.

◦ A child class can define abstract methods with the same or less restrictive visibility,
whereas a class implementing an interface must define the methods with the exact
same visibility (public).

31. what is polymorphism?


Polymorphism implies one method performing same/similar task based on the different context.
◦ There are 2 types of polymorphism
Runtime polymorphism - method overriding
Compile time polymorphism – method overloading

32. what is difference b/w method overloading and overriding?


Method Overloading
Developing multiple methods with same name but different method signatures is known as Method
overloading.
◦ The signature should change either in terms of no of arguments or its data types or
sequence of datatype.
Important
◦ 1. Method overloading applies to both static and non-static methods
◦ 2. Method can be overloaded in the same class (usually) or in subclasses.
Method Overriding
Sub class providing a new implementation of already present method (non static) in
super class
Rules for method overriding
1. There should be inheritance or ‘IS A’ relationship
2. Method should be non-static
3. Method must have same name as in the superclass with same signature and in same order
4. Return type should also be same
NOTE: Static methods are not overridden in the sub class as it is hidden.

33. what is upcasting and downcasting?


Java permits an object of a subclass type to be treated as an object of any superclass type.
This is called upcasting.
Upcasting is done automatically, while downcasting must be manually done by the
programmer

34. what is Encapsulation?


Encapsulation is the packing of data and functions into a single component and hiding the data.
It is achieved by hiding the data by making the variables private and showing the functionalities
through getter and setter methods

35. what is inheritance?


Inheriting all the members of parent class to the child class other than private members is known as
inheritance.

• The parent class is called a super class whereas the child class is known as subclass

• A sub class inherits all the members (both static and non-static) (fields, methods and
nested classes) from its super class except private members.

• Constructors are not members, so they are not inherited by subclasses, but the constructor
of the super class can be invoked from the subclass

• The inheritance can be achieved by using keyword extends. The subclass should extend the
superclass

• With the reference of subclass object we can access both the inherited member as well as
subclass member - Multilevel inheritance are supported in java

• Multiple inheritance are not allowed in java through classes

36. what is difference b/w static binding and dynamic binding?


Connecting a method call to the method body is known as binding.

• Static Binding is the binding of method body to the method call at compile time which
happens during method overloading.

• Dynamic binding is the binding of the method body of the method call at runtime which
happens during method overriding.
37. WAP to print Fibonacci series?
class fibanocci
{
public static void main(String args[])
{
int f1=0,f2=1;
int range = Integer.parseInt(args[0]);
int next=0;
System.out.println("Fibanocci Series: " + f1 + " " +f2 );
for (int i=3; i <= range;++i)
{
next = f1 + f2;
f1 = f2;
f2 = next;
System.out.print(" " +next);
}
}
}

38. WAP to print factorial of a number


class Factorial
{
public static void main(String args[])
{
int n=Integer.parseInt(args[0]);
int fact=1;
for(int i=1;i<=n;i++)
{
fact = fact*i;
}
System.out.println("Factorial of " +fact + " = " +fact);
}
}

39. WAP to print factorial of a number using recursion


public class Factorial
{
public static void main(String[] args) {

int n = 7;
int result = factorial(n);
System.out.println("The factorial of 7 is " + result);
}

public static int factorial(int n) {


if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
}
40. WAP to find the area of a circle,square and rectangle
class AreaOfCircle
{
public static void main(String args[])
{
Scanner s= new Scanner(System.in);
System.out.println("Enter the radius:");
double r= s.nextDouble();
double area=(22*r*r)/7 ;
System.out.println("Area of Circle is: " + area);
}
}

class AreaOfSquare
{
public static void main(String args[])
{
Scanner s= new Scanner(System.in);
System.out.println("Enter the radius:");
double len= s.nextDouble();
double breadth= s.nextDouble();
double area=len*breadth;
System.out.println("Area of Circle is: " + area);
}
}
41. How do you remove a value from an array?
By setting it to default value
42. Sort an array using Bubble sort
import java.util.Scanner;
public class JavaProgram
{
public static void main(String args[])
{
int n, i, j, temp;
int arr[] = new int[50];
Scanner scan = new Scanner(System.in);

System.out.print("Enter Total Number of Elements : ");


n = scan.nextInt();

System.out.print("Enter " +n+ " Numbers : ");


for(i=0; i<n; i++)
{
arr[i] = scan.nextInt();
}
System.out.print("Sorting Array using Bubble Sort Technique...\n");
for(i=0; i<(n-1); i++)
{
for(j=0; j<(n-i-1); j++)
{
if(arr[j] > arr[j+1])
{
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
System.out.print("Array Sorted Successfully..!!\n");
System.out.print("Sorted List in Ascending Order : \n");

for(i=0; i<n; i++)


{
System.out.print(arr[i]+ " ");
}
}
}

43. Write a program to reverse an array


public class ArrayReverse
{
public static void main(String[] args)
{
String names[]={"Steve","Philip","John","Johny",""};
for(int i=names.length-1;i>=0;i--)
{
System.out.println(names[i]);
}
}
}

44. Write a program to transpose a Matrix


class TransposeAMatrix
{
public static void main(String args[])
{
int m, n, c, d;

Scanner in = new Scanner(System.in);


System.out.println("Enter the number of rows and columns of matrix");
m = in.nextInt();
n = in.nextInt();

int matrix[][] = new int[m][n];

System.out.println("Enter the elements of matrix");

for ( c = 0 ; c < m ; c++ )


for ( d = 0 ; d < n ; d++ )
matrix[c][d] = in.nextInt();

int transpose[][] = new int[n][m];

for ( c = 0 ; c < m ; c++ )


{
for ( d = 0 ; d < n ; d++ )
transpose[d][c] = matrix[c][d];
}

System.out.println("Transpose of entered matrix:-");

for ( c = 0 ; c < n ; c++ )


{
for ( d = 0 ; d < m ; d++ )
System.out.print(transpose[c][d]+"\t");

System.out.print("\n");
}
}
}

45. Print values of an array at odd indexes


public class Square {
public static void main(String[] args)
{
int a[] = {1,2,3,4,5,6,7,8,9};
for(int i =0;i<a.length;i++)
{
if(i%2!=0)
System.out.println(a[i]);
}
}
}
46. Print values of an array at even indexes
public class Square {
public static void main(String[] args)
{
int a[] = {1,2,3,4,5,6,7,8,9};
for(int i =0;i<a.length;i++)
{
if(i%2==0)
System.out.println(a[i]);
}
}
}

47. Write a program to add 2 arrays


public class ArrayAddition {
public static void main(String[] args)
{
int a[][] = {{1,2,3},{4,5,6},{8,9,4}};
int b[][] = {{8,9,4},{1,2,3},{4,5,6}};
int c[][] = new int[a.length][a[0].length];
for(int i =0;i<a.length;i++)
{
for(int j = 0; j<a[i].length;j++)
{
c[i][j] = a[i][j]+b[i][j];
System.out.print(c[i][j]+"\t");
}
System.out.println();
}
}
}
48. Write a program to subtract 2 arrays
public class ArraySubtraction {
public static void main(String[] args)
{
int a[][] = {{1,2,3},{4,5,6},{8,9,4}};
int b[][] = {{8,9,4},{1,2,3},{4,5,6}};
int c[][] = new int[a.length][a[0].length];
for(int i =0;i<a.length;i++)
{
for(int j = 0; j<a[i].length;j++)
{
c[i][j] = a[i][j] - b[i][j];
System.out.print(c[i][j]+"\t");
}
System.out.println();
}
}
}

49. Write a program to demonstrate array multiplication


public class MultiplyMatrices {

public static void main(String[] args) {


int r1 = 2, c1 = 3;
int r2 = 3, c2 = 2;
int[][] firstMatrix = { {3, -2, 5}, {3, 0, 4} };
int[][] secondMatrix = { {2, 3}, {-9, 0}, {0, 4} };

int[][] product = new int[r1][c2];


for(int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++) {
for (int k = 0; k < c1; k++) {
product[i][j] += firstMatrix[i][k] * secondMatrix[k][j];
}
}
}
System.out.println("Sum of two matrices is: ");
for(int[] row : product) {
for (int column : row) {
System.out.print(column + " ");
}
System.out.println();
}
}
}

50. what are methods?


51. What is method syntax?
52. Write a method which can return two int values?
53. what can methods return?
54. write a method to find the area of a circle?
55. write a method to find the area of a square?
56. write a method to find the volume of a cube?
57. write a method to find the volume of a cone?
58. write a method to find the volume of a cylinder?
59. write a method to find the total amount to be paid principal,rate of interest and time
-all user input hint - ptr/100
60. write a method to return Orange object?
61. write a method to return marks of 4 subject.
62. Difference between throw, throws and throwable

• throw keyword is used to generate or throw an exception(existing exception class or


user defined exception) in the program.

• We can develop our own exception class by inheriting one of exception classes.

• throws keyword is used to declare the exception. throws keyword is used to throw the
checked exceptions.

• Throwable is the base class of all exception classes. It is super most class of all
exception classes

63. Difference between final, finally and finalize

• final is a keyword which is used to declare constants in java.

• Finally is a block which gets executed irrespective of whether the exception occurs or
not. It is mostly used to close the objects created using IO classes., or close the
connection of database.

• Finalize() is a method which is invoked by garbage collector in order to garbage collect


the objects that is created while program execution.

64. What is an error?


Error is a subclass of Throwable class that indicates abnormal conditions which can
cause serious problems. It should not be handled.
Ex: stackoverflow error, when we use method recursion.

65. write a program to print all the Unicode characters using casting
for (int i=0; i<=128; i++);
{
Char ch = (char)I;
SOP(ch); // applying casting and printing
}
(Or)
for (int i=0; i<=128; i++);
{
SOP((char)I); // directly printing
}
66. How do you find size of array?
int a = {1,2,3,4.5};
int len = a.length; //field of array which returns the size of array
System.out.println(length);

67. what is the minimum lines of code required to compile/execute java program?
1
68. What is the difference b/n | and ||, & and &&?
| is a bitwise operator.
|| - is a logical operation which is used to check the condition of statements. This operator
returns true if any one of the condition is true. It returns false if all the condition is false.
&& - is a logical operation which is used to check the condition of statements. This
operator returns true if all conditions are true. It returns false if any of the
condition is false.
69. what is the difference b/n parameter and argument?
Parameters refers to the definition of a method or constructor or exception to which we intend
to pass values or variables
Ex: static int add(int n1, int n2)
{

}
Here n1 and n2 are parameters
Arguments refers to values or variables which we actually pass when calling the method or a
constructor
Ex: add (100,200)
//Here 100 and 200 are arguments

You might also like