Java Notes Full
Java Notes Full
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
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.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
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.
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)
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
if (true) // works
if(age==16)// works
if(false) // works but no o/p. because the condition is false.
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
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();
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:
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.
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.
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)
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
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(:)
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
}
System.out.println("Factorial of " +fact + " = " +fact);
}
}
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("_________________________");
}
}
}
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.
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);
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.
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.
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.
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.
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);
}
}
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();
}
}
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
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.
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:
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.
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.
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.
Java String provides number of methods to work with strings like compare(),
concat(),equals(),split(),length(),replace(),compareTo(),intern(),subString()
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);
1
Returns the character at the specified index.
int compareTo(Object o)
2
Compares this String to another Object.
3
Compares two strings lexicographically.
4
Compares two strings lexicographically, ignoring case differences.
5
Concatenates the specified string to the end of this string.
6 Returns true if and only if this String represents the same sequence of characters as the specified
StringBuffer.
8
Returns a String that represents the character sequence in the array specified.
9
Tests if this string ends with the specified suffix.
10
Compares this string to the specified object.
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.
13 Encodes this String into a sequence of bytes using the named charset, storing the result into a new
byte array.
14
Copies characters from this string into the destination character array.
int hashCode()
15
Returns a hash code for this string.
17 Returns the index within this string of the first occurrence of the specified character, starting the
search at the specified index.
18
Returns the index within this string of the first occurrence of the specified substring.
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.
21
Returns the index within this string of the last occurrence of the specified character.
22 Returns the index within this string of the last occurrence of the specified character, searching
backward starting at the specified index.
23
Returns the index within this string of the rightmost occurrence of the specified substring.
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.
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.
28
Tests if two string regions are equal.
29 Returns a new string resulting from replacing all occurrences of oldChar in this string with
newChar.
30 Replaces each substring of this string that matches the given regular expression with the given
replacement.
31 Replaces the first substring of this string that matches the given regular expression with the given
replacement.
32
Splits this string around matches of the given regular expression.
34
Tests if this string starts with the specified prefix.
35
Tests if this string starts with the specified prefix beginning a specified index.
36
Returns a new character sequence that is a subsequence of this sequence.
37
Returns a new string that is a substring of this string.
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.
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.
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.
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
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”);
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
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));
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(“--------”);
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”);
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)
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.
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);
StringBuilder
StringBuilder class is also used to create mutable String. It is non-synchronized.
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));
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
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);
}
}
‘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”;
}
}
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”);
}
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
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
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.
What is Framework?
Set of guidelines that provides ready-made architecture.
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.
Syntax:
ArrayList al = new ArrayList();
ArrayList<String> al = new ArrayList<String>(); //generic way of creating
import java.util.ArrayList;
import java.util.Iterator;
for(String fruits:al)
{
System.out.println(fruits);
}
}
}
import java.util.ArrayList;
import java.util.Iterator;
Other methods:
• add()
• remove()
• addAll()
• removeAll()
• retainAll()
• clone()
• toArray()
LINKEDLIST
Java LinkedList used doubly linked list concept to store elements.
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);
}
}
}
ListInterface
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.
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;
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;
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;
}
}
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
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;
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)
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;
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.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
class Student
{
int roll;
String name;
int age;
@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;
}
}
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.
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 {
FILE HANDLING
import java.io.File;
import java.io.IOException;
public class FileDemo {
FILEWRITER Class
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 {
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 {
//Program2
import java.io.FileReader;
import java.io.IOException;
public class FileDemo {
}
}
FILEOUTPUTSTREAM Class
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 {
FILEINPUTSTREAM Class
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 {
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.
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
Student(int r, String n)
{
roll = r;
name = n;
}
}
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;
Student(int r, String n)
{
roll = r;
name = n;
}
void display()
{
System.out.println(roll);
System.out.println(name);
}
}
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)
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)
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("----");
Long.toString(100l);//ditto
Byte.toString((byte)100);
INTERVIEW QUESTIONS
1. how do you convert int to a String
int i = 10;
System.out.println(Integer.toString(i));
for(int i =0;i<s.length();i++)
{
char ch=s.charAt(i);
System.out.println(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);
}
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.
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
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.
• 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.
◦ 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.
◦ 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).
• 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
• 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);
}
}
}
int n = 7;
int result = factorial(n);
System.out.println("The factorial of 7 is " + result);
}
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("\n");
}
}
}
• 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
• 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.
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