Notes
Notes
Placements
Identifiers
Rules
1) start with alphabet ,, $(dollar)
2) we can’t start with 0-9
3) $ is used to start in java
or we can’t use dollar to start identifiers in c or c++
Variables
1)) We are using camel case for naming convention like (ranjeetTiwari)
In methods.
2) Use pascal Naming convention like (RanjeetTiwari) in Class .
3) Use capital letters like (MY_CONST) in constant.
Keywords
1) classes or function that are predefined
2) 49 keyword are predefined in java.
Data Type
Primitive
1) int -size(4byte), char -size(1byte) , float - size(4byte),
double - size(8yte)
short - size(2byte), , long - size(8byte), Boolean - size(1bit)
Byte -size(1byte).
Non- Primitive
1) String , array
Operators
1) Arithmetic : + , - , * , / , %
2) Logical : And , Or , Not .
3) Relational : > , < , => , =< , == , !=
4) Assignment : == , -= , += , *= , /=
5) Increment, decrement : ++ , --
6) Conditional : condition? (true): (false)
7) Bitwise : left shift ,right shift , & , ^
Bitwise is to increase the speed
Loops
1) For loop
For(initialisation ;condition ; increment / decrement)
{
Statement
}
Use when length is given.
2) While loop
While()
{
statement
}
When don’t know how many times loop runs.
3) Do while
Do{
Statement
}while()
When don’t know how many times loop runs.but at least one time runs.
Switch
Instead of writing many if..else statements, you can use
the switch statement.
The switch statement selects one of many code blocks to be executed:
ARRAY
Arrays are used to store multiple values in a single variable, instead of
declaring separate variables for each value.
To declare an array, define the variable type with square brackets:
String[] cars;
2) Int [] arr={1,2,3,4,5,5}
in this condition new keyword is not used so java is automatically correct
this and apply new in backend.
4) Int []a={1,2,3,44,5,};
Or
Output
2D array
Or
Int [][]a={{2,34,45},{55,67,,878}{9,899,9}}
Int c++ column size define is compulsory
If we declared
C++ is not support boundary checking. If size we declared 3*3
But we are inserting 4*4 . then c++ do.
but in java . java is not do this.
This is work on fix size.
Jagged Array
Enhance for loop is used only for data accessing. not for updating the data.
Inbuilt class
2)
3)
4)
> for descending order / which algorithm is used for sorting / complexity
5)
Placement Question
1)how a language is oops based
Ans; class and object
And support
Encapsulation, abstraction, inheritance, polymorphism
3) difference between c and c++.
Encapsulation:- wrapping of data and allowed behaviour single unit.
Why we are using encapsulation
Important component are secured
for data security.
Java is class is the example of encapsulation.
Abstraction:
Definition: Abstraction is the concept of hiding the complex
implementation details and showing only the essential features of an
object to the user. This allows the user to interact with the object
without needing to understand the underlying complexity.
Rule of Thumb:
o Data Members: Should be declared as private to protect the
internal state of the object from unauthorized access and
modifications.
o Member Functions: Should be declared as public to provide
controlled access to the data members and to expose only the
necessary operations to the user.
Access Modifiers
Access modifiers in Java determine the visibility and accessibility of classes,
methods, and variables. The four main access modifiers are:
public:
o Visibility: The class, method, or variable can be accessed from any
other class in the program, regardless of the package.
o Use Case: Use public when you want to expose a class, method, or
variable to all other parts of the application.
private:
o Visibility: The class, method, or variable is accessible only within
the class where it is defined.
o Use Case: Use private to encapsulate and protect the internal state
of a class, ensuring that it cannot be accessed or modified directly
from outside the class.
protected:
o Visibility: The class, method, or variable is accessible within its
own package and by subclasses (derived classes) in other
packages.
o Use Case: Use protected when you want to allow subclasses to
access certain members of a class while still restricting access from
non-related classes.
default (no modifier):
o Visibility: The class, method, or variable is accessible only within
the same package. This is also known as "package-private" access.
o Use Case: Use the default access modifier when you want to
restrict access to other classes in the same package but not to
subclasses outside the package.
Summary Table:
Inheritance :-
Inheritance represents the IS-A relationship which is also known as
a parent-child relationship.
Inheritance in Java is a mechanism in which one object acquires all the
properties and behaviours of a parent object. It is an important part
of OOPs (Object Oriented programming system)
when one object acquires all properties and behaviours of parent object,
it is known as inheritance
1) single
2) multilevel
3) hierarchical.
Single inheritance
When a class inherits another class, it is known as a single inheritance. In
the example given below, Dog class inherits the Animal class, so there is
the single inheritance.
Multilevel-Inheritance
When there is a chain of inheritance, it is known as multilevel
inheritance. As you can see in the example given below, BabyDog class
inherits the Dog class which again inherits the Animal class, so there is a
multilevel inheritance.
Hierarchical Inheritance
Since compile-time errors are better than runtime errors, Java renders
compile-time error if you inherit 2 classes. So whether you have same
method or different, there will be compile time error.
Msg is defined in both classes .
Aggregation:-
If a class have an entity reference, it is known as Aggregation.
Aggregation represents HAS-A relationship.
InterView Question
1) Why Method Overloading is not possible by changing the return
type of method only?
Ans-) In java, method overloading is not possible by changing the return
type of the method only because of ambiguity. Let's see how ambiguity
may occur:
2) Can we overload java main() method?
Ans- Yes, by method overloading. You can have any number of main
methods in a class by method overloading. But JVM calls main() method
which receives string array as arguments only. Let's see the simple
example:
Class Notes
in java method overloading is use but operator overloading is not
support.
InterView Question
1) Can we override static method?
Ans- No, a static method cannot be overridden. It can be
proved by runtime polymorphism.
Creating an object
Method :- mehtoad are function and procedure or sub -routines.
To excute a method , you call it from another methoad.
.) there is no rule to define parameter in methods
Method overloading:-
If two or more in a class have same name but different parameter. It is
known as method overloading.
If If two or more in a class have same parameter but differs in return
type not said to be overloaded methoad.
Constructor:-
1) Special type of method .that are calls automatically .
2) It has no return type.
3) Same name as class
Types of construction:
1) No. arg constructor
2) Parameterised
3) Non-parameterised construction
ClassName()
{
}
Eg.
Class A
{
Int a;
A(int a)
{
This.a=a;
}
1) For using same class method we are using this key word
Class student
{
Int rn
String name;
Void getData()
{
rn=10;
name=”abc”;
this.print() // that’s why this is using
}
Void print()
{
S.o.p(rn + “ ” + name);
}
}
{
Student s1=new Student();
S1.getData() //this=&s1
}
}
Class A
}
Class B extends A
{
}
Java uses extends keyword but in c++ uyse : .
Java is not support multiple inheritace directelly but indirectely
supports.
hybrid inheritance is not support because of diamond problem
More than multiple class and same name or same signature .
One problem is arrises Overriding problem.
Access specifier
1)public –
2)protected – it is modifier that allies between private and public
3)default
4) private
Class A
{
Void print();
}
Class B extend A
{
Void print();
}
Final keyword
Class A
{
Final Int a;
Final Void print()
{
S.O.P(a);
}
}
1) With final we create constant .
2) Not override . that it gives the error
Eg. Class A
{
Final Int a;
Final Void print()
{
S.O.P(a);
}
}
Now we creating
Class B extend A
{
Void print(); /// that are not allowed because method is iniitilise in base class
with final
}
Int b;
Public Demo()
{
Super();
b=20;
}
Class Example{
P.S.V. main(string[] a)
{
Test d1= new Demo()
D1.print() ;//it print the demo class// it is the dyanamic dispatch
Test d2=new Test()
D2.print()//it print parent classggg!!!!
}
}
Static methods are not polymorphic. This means that the method called is determined at
compile time based on the reference type, not the object type.
In this case (a) is reference of A and object of B. and when we call (a.cq1()). Then it call to
the object of class
But if cq1() method are static then things does’t like Previos .
Int which the reference of (a) is A and object is B .. then we call a.cq1().
Then it call to the reference type class.
Bitwise operator
Binary
1) OR
2) AND
3) EXOR
4) SIGNED RIGHT SHIFT
5) SIGNED LEFT SHIFT
6) UNSIGNED RIGHT SHIFT
Unary
1) N (complement)
Precedence
1) ~ --right to left
Eg. ~N=-(N+1)
public static void main(String[ ]a)
{ System.out.println(~(-9));
}
ABSTRACT
A class which is declared with the abstract keyword is known as an abstract
class in Java. It can have abstract and non-abstract methods (method with the
body).
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only
functionality to the user.
Another way, it shows only essential things to the user and hides the internal
details, for example, sending SMS where you type the text and send the
message. You don't know the internal processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
Ways to achieve Abstraction
There are two ways to achieve abstraction in java
1. Abstract class (0 to 100%)
2. Interface (100%)
Abstract class in Java
A class which is declared as abstract is known as an abstract class. It can have
abstract and non-abstract methods. It needs to be extended and its method
implemented. It cannot be instantiated.
INTERFACES
2) It more understandable
Out put
Ans.)
1) When you create a class like Rectangle without explicitly defining a
toString() method, the default toString() method from the Object
class is used.
2) returns a string that consists of the class name followed by the "@"
character and the hexadecimal representation of the object's hash
code
STRING
1) String class is used to create string object .
2) In c++ String has no null character at last if we create with String
keyword
3) Declaration
String s1=”Ranjeet”
String s2=”Ranjeet” // will not create new instance
7) String s1=”Isha”;
String s2=”Sharma”
S1=s1+s2;
JVM uses string buffer concept behind it
8) String s=new StringBuffer("").append(s1).append(s2).toString();
9) Java is safe it is not giving the exact address. If we want to extract we
cant use System.out.println(s.hashCode());
It generate the hashcode of adsress
11) Concate
Ans 10Coding30
12) IndexOf()
Eg. Return the index of character. and give the first occurance
Ans – 2
Ans – 7
Ans – 7
13) LastIndexOf()
It search from the and. If character or sting is not found then gives the
Answer is -1
Ans – 7
14) toCharArray()
15)
16) Contains()
Ans true
Return the answer in form of Boolean
17) Replace
It is replace all the occurance
Ans – cooing oi
18) String.format
String formatting allow us to control the presentation of text and
numeric value in the string.
It is static method
Format method has system class
Output
19) ==
It check the address
Output is false
20) CompareTo()
The java compares two string based on the inocode value of each
character in string.
Output in Integer
output is 0 . if it is 0 then the string is equals else not equal;
Output
output
21) startWith()
Ouput
22) endWith()
Ouput
23) Split()
24) Join()
Output
StringBuffer()
1) StringBuffer is Synchronised .. means sequence by sequence.
2) StringBuffer take more time run.
Because of synchronised.
3) thread safe. Because it is Synchronized.
1) it is not java,lang pakage no need to import.
Example
1) Length() , capacity()
Output
2) Append()
Output
3) Reverse()
Output
4) Insert()
Output
StringBuilder
1) Mutable String
Ans JDK provide this mutable classes
Output
String Tokenizer()
1) Create token of string with the help of deliminator.
2) Tokenizer need to import because it is in java.lang.utill.
And utill need to import.
Example.
1)
Output
Question of String, StringBuilder, StringBuffer
Ques. 1)
Ques. 2)
Ques. 3)
Ques. 4)
Exception Handling
Java provides superior support for runtime error and exception
handling, enabling programs to check for anomalous conditions and
respond to them with minimal impact on the normal flow of
program execution. This allows error- and exception-handling code
to be added easily to existing methods.
Throw
Purpose: Used to actually throw an exception from a method or a block
of code.
Usage: You use throw when you want to create and throw an instance of
an exception. It is used within the method's body to indicate that an
error has occurred.
Throws
Purpose: Used in the method signature to declare that a method can
throw one or more exceptions. This is a way to inform the caller of the
method that they should handle or declare these exceptions.
Usage: You use throws in the method declaration to specify that the
method may throw certain types of exceptions. It is part of the method's
signature.
try-catch-finally
At least one catch clause or finally clause must be defined. More than
one catch clause may be used, but no more than one ly clause may be
identified
Step to be follows:
1) The try statement executes a statement block.
2) If an exception is thrown during the block's execution, it terminates
execution of the statement block.
3) and checks the catch clauses to determine which, if any, of the catch
clauses can catch the thrown exception.
4) If none of the catch clauses can catch the exception, the exception is
propagated to the next level try statement.
Mismatch exception
Solved like this
Exception catch will be in the end.if we put in starting then ambiguity arises
3) Change the value in Method: Java supports only call by value. So,
if we pass a primitive value, it will not change the original value.
But, if we convert the primitive value in an object, it will change
the original value.
AutoBoxing
1) The automatic conversion of primitive data type into its
corresponding wrapper class is known as autoboxing.
for example, byte to Byte, char to Character, int to Integer, etc.
2) Since Java 5, we do not need to use the valueOf() method of
wrapper classes to convert the primitive into objects.
Unboxing
1) The automatic conversion of wrapper type into its corresponding
primitive type is known as unboxing. It is the reverse process of
autoboxing.
2) Since Java 5, we do not need to use the intValue() method of wrapper
classes to convert the wrapper type into primitives.
Generics
1) The Java Generics programming is introduced in J2SE 5 to deal with
type-safe objects. It makes the code stable by detecting the bugs at
compile time.
2) Before generics, we can store any type of objects in the collection,
i.e., non-generic. Now generics force the java programmer to store a
specific type of objects.
There are mainly 3 advantages of generics. They are as follows:
1) Type-safety:- : We can hold only a single type of objects in generics. It
doesn?t allow to store other objects.
Without Generics, we can store any type of object
Generic class
1) A class that can refer to any type is known as a generic class. Here, we
are using the T type parameter to create the generic class of specific
type.
2) Let's see a simple example to create and use the generic class.
Generic Method
1) Like the generic class, we can create a generic method that can
accept any type of arguments. Here, the scope of arguments is
limited to the method where it is declared. It allows static as well as
non-static methods.
2) Let's see a simple example of java generic method to print array
elements. We are using here E to denote the element
Output
Type Parameters
The type parameters naming conventions are important to learn
generics thoroughly. The common type parameters are as follows:
T - Type
E - Element
K - Key
N - Number
V - Value
Collection
The Collection in Java is a framework that provides an architecture to store
and manipulate the group of objects.
List Interface
A list is an ordered collection of elements which may contain duplicate .
it is an interface that extends the collection collection interface . lists are
further classified into into the following.
3) ArrayList
Arraylist is the implementation of list interface where
Hashmap
Java HashMap class implements the Map interface which allows us to
store key and value pair, where keys should be unique. If you try to insert
the duplicate key, it will replace the element of the corresponding key.
Sysntax
HashMap<keyType,valuetype> mymap=new
HashMap<keyType,valueType>
Iterate
Hashset
A list can contain duplicate elements whereas Set contains
unique elements only.
Syntax
HashSet<E> hs=new HashSet<E>();
Can store 16 capacity and default load factor is 0.75
Queue
1) The interface Queue is available in the java.util package and does
extend the Collection interface
2) It is used to keep the elements that are processed in the First In
First Out (FIFO) manner.
3) It is an ordered list of objects, where insertion of elements occurs
at the end of the list, and removal of elements occur at the
beginning of the list.
Java Stack
1) The stack is a linear data structure that is used to store the
collection of objects
2) It is based on Last-In-First-Out (LIFO).
Vector
Vector is like the dynamic array which can grow or shrink its size. Unlike
array, we can store n-number of elements in it as there is no size limit.
Multithreading
Java supports single-thread as well as multi-thread operations. A single-
thread program has a single entry point (the main() method) and a
single exit point. A multi-thread program has an initial entry point (the
main() method), followed by many entry and exit points, which are run
concurrently with the main(). The term "concurrency" refers to doing
multiple tasks at the same time.
policy
MIN_PRIORITY=1
NORM_PRIORITY=5
MAX_PRIORITY=10
2) Runnable interface
Files
1) FileWriter
This is used to write character-oriented data to a file.it is
character oriented class. Which is used for file handing in
java
KeyPoint for exam
Inheritance
1) If set a default value. The method is that means that cannot override.
So we can do that this with super keyword in contructor
Eg. Is in marketer question.