0% found this document useful (0 votes)
16 views

Java NOTE

Uploaded by

suneha2003datta
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Java NOTE

Uploaded by

suneha2003datta
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 13

/

JVM
----------

JDK=JRE(JVM is a part with jre and its a heap area) +JAR


javac inside jvm converts java code into a byte code with .class extension

NORMAL SYNATX TO KNOW


----------------------
s.charAt(i) or sb
sb.setCharAt(i,ch) sb.insert(i,"") sb.deletecharAt(i) sb.delete(start,end-1)
sb.reverse() sb.capacity() sb.ensureCapacity() sb.trimToSize()
System.out.print
Console console = System.console();
Scanner sc= new Scanner()
sc.nextInt() nextDouble ,
(int)Math.random()
public int hashcode();// to gennerate unique no of each obj
difference between String and StringBuffer -- stringbuffer uses the same object
can be mutable unlike string that creates a new object again and immutable
s.concat("") sb.append(""); s.equalsIgnoreCase("") s.substring(startingindex)
s.substring(start,end-1) s.replace('each old char','')
equals is not overriden in StringBuffer
s.toUpperCase() s.trim() s.indexOf()
use of "var" keyword
_______________________________
___________________________________________________________________________________
________________________________________________________________
ACTUAL CONCEPT OF OBJECTS AND CLASSES/LOCATION OF VARIABLES AND METHODS IN THE
MEMORY // CLASS AREA AND STACK
what is class?
it is nothing physical . it is just a concept . class is a keyword used to specify
the compiler that the next part within{} is a just a DEFINITION of SOMETHING WHICH
WAS PREVIOUSLY NOT KNOWN TO THE COMPILER.
we give each such definitions a name suppose class Helloworld, class suvo, class AB
etc each such definition is unique of its own kind .
EXACT EXAM DEFINITION OF CLASS -- class is a user defined data type with memeber
variables and member methods.

what is scope?
anything within a {} is a particular scope

what is an object
objects are special variables which are like pointers or reference variables which
can store address OF SOME MEMORY BLOCK WHICH LIKES ACCORDING TO THE DEFINITIONS OF
ANY PARTICULAR CLASS.
using that address present in that object / reference variable we can access all
the properties "the member variables & the member methods" of each of those MEMORY
BLOCKS.

AB varr = new AB();


AB varr2 = new AB();
AB varr3 = new AB();
each varr1, varr2, varr3 are objects which all contains diffrent address to three
different memory blocks where all those memory blocks ""look"" according to the
definition defined in the class AB;

what is static keyword?


static is a keyword used to tell the compiler that "" DEKHO VAI TUMI EI CLASS ER
DEFINITION ONUJAI JESAB OBJECTS/reference variable pointing to a memory block I
BANAO NA KNO PROTTEK TAR JNNO ALADA KORE MEMBER VARIABLES ER COPY BANABE NA EKTAI
VARIABLE / FUNCTION BANABE FOR ALL OBJECTS MAKE A SINGLE VARIABLE / A SINGLE
FUNCTION which is THUS
A PROPERTY NOT OF OBJECTS rather that specific variable can be accessed by that
class name only.

## thats why we write static in case of main() method. JATE ALADA KORE OBJECTS NA
BANATE HOI DIRECTLY FILE NAME/ CLASS NAME DIE I main() ke call kora jai.

NOTE AFTER COMPILATION JOTOKOTA CLASS ER DEFINITIONS AMRA BANAI TOTOKOTAI .class
files toiri hoi for each of those classes defined in the main java file before
compilation .

what is "this" keyword?


"this" is used to tell the compiler je " ami jei object tar jnno function ta call
koreci tumi sei object ta je memory block ke point korece tumi sudu sei memory
block tai thaka member varibales er copy gulo bojacci.

EXAMPLE CODE

class AB
{
public int a;
public int b;

public void add(int x, int y)


{
this.a =x;
this.b = y;

System.out.println(a+b);
}
}

class Mainclassabcd
{
public static void main()
{
AB varr = new AB();
AB varr2 = new AB();
AB varr3 = new AB();
varr.add(1,2);
varr2.add(3,4);
varr3.add(67,89);
}
}

___________________________________________________________________________________
___________________________________________________________________________________
____________
DYNAMIC DISPATCH- INHERITANCE
-----------------------------

Compile-time Type: This is the type declared for the reference variable. In your
case, it's Animal myAnimal.
Runtime Type: This is the actual type of the object the reference variable is
pointing to. In your case, it's new Dog().
Method Invocation:
At compile-time, the compiler checks if the methods called on myAnimal are declared
in the Animal class. It doesn't have information about the actual runtime type of
the object.
At runtime, the JVM uses the actual type of the object (Dog in this case) to
determine which overridden method to invoke.
myAnimal = new Cat(); //in case of changing directly to another subclass
flexibility;

Superclass x = new Subclass();


Subclass y = (Subclass) x; this is valid.

Superclass x = new Superclass();


Subclass y = (Subclass) x;
We cannot do this typecasting.

the reference in java is differrent from pointers in C . in java reference is a


type of variable which holds address too but it can hold only address of a specific
type therefore if its a parent class address then it can hold even subclass objects
which all extend it .
in compile time the compiler does not care whether the Animal A obj is new
Animal() or new Dog() that's what the runtime takes care of it just considers in
compile time whether A which is of type Animal has the method invoked on A or not?

dynamic dispatch refers to the "refernce concept" && method overriding links to the
runtime function call behavior which is a product of DD
Animal myAnimal = new Dog();
___________________________________________________________________________________
___________________________________________________________________________________
______________
METHOD OVERLOADING AND METHOD OVERRIDING - INHERITANCE
------------------------------------------
Method Overloading: In method overloading, multiple methods in the same class have
the same name but different parameter lists (different types or different numbers
of parameters).
Method Overriding: In method overriding, a subclass provides a specific
implementation for a method that is already provided by its superclass. The method
signature (name, return type, and parameter types) in the subclass must be the same
as that in the superclass.

___________________________________________________________________________________
________________________________________________________________________
___________________________________________________________________________________
_____________________________________________________________________

ARRAY
----------
Annonymous array S.O.P(new int[] {1,2,3,4,5}) func(new int[] {1,2,3,4})
int[] var = {1,2,3}//static
int var = new int[10]//dynamic
Arrays.sort(arr)
Arrays.equals(arr1,arr2)
ob == ob2 [checks by address therefor maybe givivng not equal even if same element
having array ]
arr.length
s.length()
int arr[][] = new int[3][5] OR int arr[3][] ; arr[0]= new int[5] arr[1] = new
int[4] arr[2] = new int[6];
___________________________________________________________________________________
____________________________________________________________________
___________________________________________________________________________________
_____________________________________________________________________
STATIC KEYWORD
----------------
within any class we can have both static and non static functions . within the
class we can call the methods just by name but outside the functions we need to
create the objects for non static functions and just call by classname.method() in
case of static methods of that class.
-----------------------------------------------------------------------------------
-----------------------
But within the class if any method is called within any static method then that
called must also be static if used with only name of method , Since we cannot use
this.method() without creating object since methods have to be static or else we
have to create an object of that class itself an then call that method by that
object name

class Use
{
public void fun()
{
HelloWorld.ok();
System.out.println("hello ji");
check();
}
public void check()
{
System.out.println("call me whenever you want me within you");
}
}// within a static method if i call a function or variable even if of the same
class then if we use only function name or variable name then it will be a compile
time error if that method or variable is also not static but thats not the case if
within which it is called is also not static.
class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
Use ob = new Use();
ob.fun();
ok();
HelloWorld ob1 = new HelloWorld();
ob1.hi();
}

public static void ok()


{
System.out.println("I am a function of the main class which needs no onj
can be called just by name within the class itself as known and by class name
outside it");
}
public void hi()
{
System.out.println("I am a function of the main class which needs an obj");
}
}

___________________________________________________________________________________
________________________________________________________________________
________________________________
final keyword: used before any variable to make it constant or any method to stop
it from being overriden or class so that no child of it can be made
finalize() ---- it is a method called before destrying any unused porethaka object.
___________________________________________________________________________________
_________________________________________________________________________
INTERFACES & ABSTRACT CLASSES
-----------------------------------------------------------------------------------
--------

Interfaces can have abstract as well as default functions


We don't need to mention abstract keyword in those functions.
Always contain final data members.
Interfaces don't have any object.
Any child class has to implement all its functions.
We may or maynot override default methods.
If any class is abstract then abstract keyword must be used.

Abstract class in java can't be instantiated. We can use abstract keyword to create
an abstract method, an abstract method doesn't have body. If a class have abstract
methods, then the class should also be abstract using abstract keyword, else it
will not compile

The subclass of abstract class in java must implement all the abstract methods
unless the subclass is also an abstract class

so is it like in inheritance it is achieved by extends keyword and also the


subclasses can inherit all the behaviors as well as properties but also can change
any particular behaviour or even add new behaviours . Where as if one implements
any class then it becomes a subtype and "will provide definitions of all the
behaviours stated in the superclass which is implemented and therefore it can be
similar to the type of many interfaces" whereas it can extend only one class
Abstract classes are classes which has one or more abstract methods and we cannot
make objects of this abstract class. if ny other class extends this abstract class
then its has to provide definitions to all the abstract methods present in the
parent class. if any abstract class has other functions which are not abstract then
the subclass cannot override those defined functions. Interfaces are not classes
rather a new type of modularisation where implicitly abstract and also supporting
multiple subtyping " a new concept " = VARIATION(INHERITANCE + ABSTRACT CLASS)

___________________________________________________________________________________
___________________________________________________________________________________
___________________________________________________________________________________
_______________________________________________________________

EXCEPTION HANDELING:

there are two types of errors compile time error & run time error:
compile time error = syntax error

------Throwable //runtime error


----Exception // internal code logic was not right
-----Error // Ststem fail
run time error - is a situation when either the code fails or the jvm itself fails.
this situation is conveyed to the programmer in the form of a "sentence or a
string". BUT HOW?
IN general all such common run time error situations are made into several classes
in java.lang package . Since all classes are subclass of Object class thus through
overriding toString() method they express the class as a String message.
We have a class known as Throwable which has two subclass 1.Execption (mainly for
code fails) 2.Error (when jvm fails to handle that condition like memory nei ar)
we generally use this Execption class for our purpose to handle run time COMMON
errors like ""ArrayIndexOutOfBounds/ArithmeticExecption"" etc . Like this the most
common such run time errors when the code fails are classified and pre defined as
different classes under the Exveption superclass. But if we want we can also make
our own situation to handle by creating a new class inheriting the Exception
class.

DEFAULT EXCEPTION HANDELING BY JVM:


it prints the execption that happened as an object in form of a string// and then
TERMINATES THE REST OF CODE
(name,description,stack trace)
SYNTAX TO HANDLE THOSE EXECPTIONS BY OURSELVES WITHOUT TERMINATING THE REST CODE :

try
{

}
catch(typeofExecption e )
{
// jakon nijesso bananop kono logical error define krce erm object banate chai
throw e;
}
finally{

// throws
here e is an object thrown which is of the type of "ANY OF THE PEVIOUSLY MENTIONED
CLASSES" whenever the code inside the try block fails

under Execption class hierarchy :


1.RuntimeException-
ArrayIndexOutOfBounds
ArithmeticExecption
NoClassDefFoundException
ClassCasteException
NullPointerException
IllegalArgumentException

2.IOException
EndOfFileException
FileNotFoundExecption --- this class is a checked exception throws
FileNotFoundExecption
InterruptedIOException

3.ServeletException
4.RemoteExecption
5.InterruptedException

#only the first unchecked uncaught execption is catched in running state


#multiple try with multiple catch
#try with finally without catch
#nested try catch
# one try with multiple catch [when the type of execption is not known]

#checked Execptions- the exceptions checked by the compiler that can possibly occur
at runtime but has not occured yet since code has not run yet . Ex-unreported
exception in file handeling [[[[[[USE OF "throws" KEYWORD AFTER THE FUNCTION
DECLARATION]]]]]
#unchecked - Ex- ArithmeticException etc

--functions of an exception object


printStackTrace
getMessage

FOR USERDEFINED EXCEPTION CLASSES-- the jvm itself cannot throw this type of
object we need to throw it using "throw" keyword
also throw keyword can be used for AE()
ALL CHECKED EXCEPTIONS MUST BE CAUGHT OR DECLARED BEFORE THE FUNCTION

class OurownException extends Exception


{
OurownException(String s)
{
super(s);
}
}
___________________________________________________________________________________
___________________________________________________________________________________
___________________________________________________________________________________
_______________________________________________________________
THREAD

#process based AND thread based


#define a thread for every independent peice of code

class Mythread extends Thread / implements Runnable


{
// thread can have constructors to set some values
p s v run()
{CODE}
}
in main method create a thread and s.start()
difference between normal code output by run method direct calling AND new thread
creating by start method so not recommended to override start method and overload
run method.
if implementing Runnable then Thread t = new Thread(new MyThread()) t.start();
--- constructors of Thread class
---methods of Thread class
currentThread()
setName()
getName()
stop()
suspend()
resume()
p f v .setPriority(int x)
Thread.yield() // to hold the call for some time to give chance to others of same
priority otherwise you only continue [written in run()]pco booth example
ENTER INTO READY STATE
x.join() in y thread // thus y waits until x gets COMPLETED. /// if not best
friend x.join(long ms)
ENTER INTO WAITING STATE
sleep()
t.interrupt() /// so if t thread anytime goes to sleep it will be interrupted by
someone else ruuning
--- -----------------------------methods callable only within any synchronized
block -----------------------------------
wait() // to wait for a particular thread to perform updation on any object so we
write obj.wait() within that thread
notify() notifyAll() // to notify all other threads if anyone waited for it when i
want to notify

// Java program to demonstrate the use of wait() method


class GunFight {
private int bullets = 40;

// This method fires the number of bullets that are


// passed it. When the bullet in magazine becomes zero,
// it calls the wait() method and releases the lock.
synchronized public void fire(int bulletsToBeFired)
{
for (int i = 1; i <= bulletsToBeFired; i++) {
if (bullets == 0) {
System.out.println(i - 1
+ " bullets fired and "
+ bullets + " remains");
System.out.println(
"Invoking the wait() method");
try {
wait();
}
catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(
"Continuing the fire after reloading");
}

bullets--;
}
System.out.println(
"The firing process is complete");
}

// reload() increases the bullets by 40 everytime it is


// invoked and calls the notify() method which wakes up
// the thread that was sent to sleep using wait() inside
// of fire() method
synchronized public void reload()
{
System.out.println(
"Reloading the magazine and resuming "
+ "the thread using notify()");
bullets += 40;
notify();
}
}

public class WaitDemo extends Thread {


public static void main(String[] args)
{

GunFight gf = new GunFight();

// Creating a new thread and invoking


// our fire() method on it
new Thread() {
@Override public void run() { gf.fire(60); }
}.start();

// Creating a new thread and invoking


// our reload method on it
new Thread() {
@Override public void run() { gf.reload(); }
}.start();
}
}

-----------------------------------------------------------------------------------
-------------------------------------
#default priority = 1 to 10 [ FOR MAIN THREAD ITS 5 AND OTHERS INHERIT FROM
PARENT AS DEFAULT but we can also set it ] // we can also set priority of main
thread
-----------------------------------------------------------------------------------
------------------------------------
Demon thread

threads working in background - GC,


t.setDaemon(True) //only before starting a thread
isDaemon()
if last nondemon thread completes all demon is stopped
-----------------------------------------------------------------------------------
------------------------------------
THREAD ENHANCEMENT
1. ThreadGroup class - used to create Thread groups - System-main-new
ThreadGroup(parent group,"name") Thread t1 = new Thread(tg1,new
MyRunnable(),"one");
2.util.concurrent.locks package - it says if lock is not available you dont wait
telling to the synchronized block ...you please do other stuff
Lock interface , [[obj.trylock() obj.lock() obj.unlock() ]]within any thread
obj.getOwner()
all these only ob objectes created as a Lock class ReentrantLock of Lock interface
___________________________________________________________________________________
_____________________________________________
SYNCHRONIZATION--to provide synchronised userdefined locks kinda

synchronized keyword for any method or block of code. If multiple threads are
trying to operate on the same java object then this keyword helps to perform
methods of that object one by one by all the threads using it.//when a thread takes
an object as constructor parameter and uses it in its run method.
use of static synchronized usage
synchronized(this){} // if any thread has a lock on this object then only it can
access this area now
synchronized(classname.class){}
___________________________________________________________________________________
_____________________________________________
________________________________________________________
WRAPPER CLASSES-- autoboxing
all these are child classes of wrapper class
classes used to convert primitive type to object type
Integer() //static methods -- .tostring(), .valueOf(99) parseX("string",int
radix--which will be converetd to that Xclass)
Double()
// object methods .byteValue(), .shortValue() etc
Integer i = new Integer(-8);

// 1. Unboxing through method invocation


int absVal = absoluteValue(i);
___________________________________________________________________________________
_____________________________________________
________________________________________________________
CLONING

to create many objects at a time of a particular class


the class must implement Clonnable
(typecaste to class of it)ob.clone();
___________________________________________________________________________________
_____________________________________________
________________________________________________________
VAR ARGS

m1(int .......x){} var args method


static void fun(int... a)
{
for (int i : a)
{System.out.print(i + " ");}

}
fun(1,2,3,5)
___________________________________________________________________________________
_____________________________________________
________________________________________________________
LAMBDAS
to instantiate any object with direct class defination implementing any interface
having only one method
interfacename ob = new interfacename(){write defination of method as normal
definition}
OR
ineterfacename ob = (method parameters)->{method definition as just statements of
code }

another application--- We can even pass it(single function corresponding to an


interface) to an other function who uses that interfaces's child objects' function
as-- Arrays.sort(arr,(String s1, String s2)->{s1.length()-s2.length()}) /// as a
definition of the Comparator interface's compareTo() function

we can also pass static methods as


scores.merge(key,value,Integer::sum) OR scores.merge(key, value,(a,b)-
>Integer::sum(a,b)) // this special merge function accepts a function
// here the {} can be written like a static method
equivalent statements :
scores.merge("a", 50, (oldValue, newValue) -> objused.updateScore(oldValue,
newValue));
scores.merge("a", 50, objused::updateScore);
___________________________________________________________________________________
_____________________________________________
________________________________________________________
GENERICS
arrays are type safe unlike collections
failing the program at compile time is better than at runtime
collectionname <typename> ob = new collectioname<typename>() typename cannot be
primitive type
class Ourownclass<T> // <T extends Number > // <T extends Ainterface> // <T
extends classname & multipleinetrfacename> //<T,F> // super not possible
{
public T method(T a) //when we donot know what single value has its type as
{
return a;
}

}
class Ourownclass
{
p v method(AL<?> a)// when we know which collection is it but not its type of
things inside it or else AL<String> // here also extends/supper possible
{
return "ok";
}

}
Ourownclass<Integer> ob = new Ourownclass<Integer>()
Ourownclass<Integer,String> ob = new Ourownclass<Integer,String>()
AL<? or ? extends Number> ob = new AL<Integer>()
//Yes, it is valid <Object> but not purpose serving

when class not using any type T


public <T>void method(T a){// this T before can be used anywhere within the
parmeter defination or statement definitions}

generics only at compile time so here is a proof


AL ob = new AL<String>()
AL.add(10) -------no compile time error since ob is AL general type but ALSO NO
RUNTIME ERROR TOO
___________________________________________________________________________________
_____________________________________________
________________________________________________________
STREAMS

A class present in java.util Streams which is provides some functions for stream
objects . This object has no such represenation like Lists its used to directly
invoke some functions to perform iterartive abilities by converting List objects
to stream objects

Stream s =listl.stream() OR .parallelstream() // if array then Stream.of(arr)


s.filter(lambda expression).count()
Stream.generate(lambda function telling to do something like printing)
Stream.iterate(0,n->n<100,n->n+1)
s.map(lambda function) // used to map i to f(i) for each member of stream s /
flatmap(lambda)
s.limit(int) s.drop(int) s.takewhile/dropwhile(lambda)
___________________________________________________________________________________
_____________________________________________
________________________________________________________
ENUMS

group of named constants under one name like


enum Month
{JAN,..;}// all are implicitely psf
but JAVA enum can have methods, class anything
Month m = Month.FEB; // m = FEB in string value
enums can be defined within a class or outside not inside any method
enum can implement but not extend
Month[] m = Month.values()
Month.JAN.ordinal() = 0
we can even run main in an enum rather than a class
we can write a constructor within the enum but we cannot instantiate any enum
object as Month()
***setting price of beer ***
___________________________________________________________________________________
_____________________________________________
________________________________________________________
LOGGING
a class used to get metadata
present in java.util.Logging
Logger.getGlobal().info("activity message") // .getLogger()
Logger.setLevel(Level.OFF) // Level.ALL .FINE .SEVERE etc
___________________________________________________________________________________
_____________________________________________
________________________________________________________
ASSERTIONS
for debugging

assert(bool condition) // otherwise AsertionError


ingenerally disabled
java -ea file
assert(bool cond.):"String "
assert(bool cond.): x++; / :m1(); //method must return not void
___________________________________________________________________________________
_____________________________________________
________________________________________________________
OPTIONAL TYPES%%
___________________________________________________________________________________
_____________________________________________
________________________________________________________
FUNCTIONS%%
___________________________________________________________________________________
_____________________________________________
________________________________________________________
SERIALIZATION

reading or sending objects across networks


___________________________________________________________________________________
_____________________________________________
________________________________________________________
PACKAGES
javac -d a.g.j.Test.java
java a.g.j.Test
___________________________________________________________________________________
_____________________________________________
________________________________________________________
File/IO
_______________________________________________________________
INFORMATION NORMAL
-----------------------
1.we can override two methods of the superclass Objects of all classes that is
toString() and equals() by @Override
2.Arrays , Scanner in java.util.*
3.static keyword is used for only one memory allocation hence if not called with
class name rather by object name or by this. it will print the last updated value.
4.class is a user defined datatype that encloses member variables and member
methods.
5.In case of overriding the return type should be same
6.this() is actually the constructor , this keyword is used when we use variables
of class with the same name of the parameters passed then to tell that is also not
a local variable we use this
7.when performing any operations largest size er variable ar je return type the
result has that return type implicitely
8.byte widening effect in any operations with byte only . ------> to int NEED FOR
TYPECASTING
9. Garbage Collector destroys only heap objects.
10. widening dominates both autoboxing and var agrs method where the latter is of
least priority

//inner class
//length
//
//String x = "Suvadip" x.length()
// x ={1,2,3,4} x.length

/* for(i=0;i<=x,length();i++)
{
if(x[i]=='e')
{
print ok;
}
}*/
/*
* class CarMaking
* {
*
* class Tyre
* {
*
*
* }
*
*
* }
*
*
*/

You might also like