Java Core

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 29

7***********Constructor – NO RETURN(ITS VOID)

SAME NAME AS CLASS ITS FORMED IN

Its a way of setting value for an object,ex = Al3 obj = new Al3(3,9);
we just gav parameters

***********NON ACCESS MODIFIERS

*****FOR ATT/METHODS

1)Final =Att and methods cant be modified.

2)Static=ATT/METHOD BELONGS TO A CLASS,WE don’t hav to make


an object to initialize a static method of a class.Also a normal
method cant call a static,only static method can do so,same goes
for att.

3)Abstract=Methods are left empty and their body is filled in the


extended class(child class)

*****FOR CLASS

1)Final=We can’t extend this class i.e no inheritance.

2)Abstract=We can’t make objects of this class,w gotta extend it i.e


imply inheritance.

***************PACKAGES

Packages are nothing but collection of classes and their methods in


there.

Import Package.name.class; // import package.name.*;

***************INNER CLASSES
WE CAN HAVE CLASS INSIDE OF A CLASS.

Then we can excess the object inside inner class by using


OUTER.INNER name = new OUTER.INNER();
class OuterClass {

int x = 10;

private class InnerClass {

int y = 5; }

public class Main {

public static void main(String[] args) {

OuterClass myOuter = new OuterClass();OuterClass.InnerClass myInner = myOuter.new InnerClass();

System.out.println(myInner.y + myOuter.x); }}

TYPES;

1)Private inner class=If you try to access a private inner class from an outside class, an error occurs

2)Static inner class=An inner class can also be static, which means that you can access it without creating an object of the outer class

************INTERFACE

Its a static class i.e it holds all methods without body(as they all are
static from inside)

interface Animal {

public void animalSound(); // interface method (does not have a


body)

public void sleep(); // interface method (does not have a body) }

class Pig implements Animal {

public void animalSound() {

System.out.println("The pig says: wee wee");}

public void sleep() {System.out.println("Zzz"); } }


*******************ENUMS

Stuffs that can’t be modified.Sorta class of constants(They should


be in UPPERCASE letters.)

public class Main {

enum Level {

LOW, MEDIUM, HIGH }

public static void main(String[] args) {

Level myVar = Level.MEDIUM; System.out.println(myVar); }}

1)We can use it in switch stm


enum Level {

LOW, MEDIUM, HIGH }

public class Main {

public static void main(String[] args) {

Level myVar = Level.MEDIUM;

switch(myVar) {

case LOW: System.out.println("Low level");break;

case MEDIUM: System.out.println("Medium level");break;

case HIGH: System.out.println("High level");break;

}}}

2)We can use it in for each loop using values() method

enum moods{

ANGRY; HAPPY; BLUE; }

Main(){

For(moods Var : moods.values() ) { /// body } }

********************TIME IN JAVA
Import java.time.*; // package

Or alot of classes =>


import java.time.LocalDateTime; // Import the LocalDateTime class

import java.time.format.DateTimeFormatter; // Import the DateTimeFormatter class

public class Main {

public static void main(String[] args) {

LocalDateTime myDateObj = LocalDateTime.now();System.out.println("Before formatting: " + myDateObj);

DateTimeFormatter myFormatObj = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");

String formattedDate = myDateObj.format(myFormatObj); System.out.println("After formatting: " + formattedDate);

}}

Other classes;

LocalDate ; LocalTime ; LocaDateTime; DateTimeFormatter;

******************ARRAYLIST

ArrayList<String> cars = new ArrayList<String>();

We can change its size later as well after defining unlike an array.

*****We use add(); get(); size(); set(index num,element); clear();


[emptiesit] remove(index);[removes an individual element]

*****We gotta use Integer,Boolean,String,Character(i.e classes not


primitive types)

*******import java.util.ArrayList; import java.util.Collections;

Collections.sort(cars); THIS BAD BOY SORTS THE ARRAYLIST CALLED cars

******FOR EACH LOOP for (String i : cars) {

System.out.println(i);
************************LINKEDLISTS

Both are same but linked is used to manipulate data and arraylist is
used to store data

******Arraylists;When we add a new element old arraylist is


destroyed and a new one is made up with a higher size n so.

WHILE IN Linkedlist;Its like every thing is stored in a container and


1st container is having link to the list while when we add a new
element ,that containers link is given the one that comes prior to it.

**** addFirst(); addLast(); removeFirst(); removeLast(); getFirst();


getLast();

********************HASHMAPS

***OUTPUT {USA=Washington DC, Norway=Oslo, England=London, Germany=Berlin}

Int it things go upside down with a logic similar to 2D array. But with key/value concept

Here USA IS KEY FOR WASHINGTON DC AND SO ON.

***OPERATIONS import java.util.HashMap; // import the HashMap class

HashMap<String, String> capitalCities = new HashMap<String, String>();

capitalCities.put("England", "London");capitalCities.get("England");capitalCities.remove("England");

capitalCities.clear(); capitalCities.size();

***WE can do mapping of Strings to an Integer;and varooius kinds.

******************HASHSETS
import java.util.HashSet; // Import the HashSet class

HashSet<String> cars = new HashSet<String>()cars.add("Volvo");

cars.contains("Mazda"); cars.remove("Volvo"); cars.size();

for (String i : cars) {

System.out.println(i); }

**************************ITERATOR
An Iterator is an object that can be used to loop through collections

Note: Trying to remove items using a for loop or a for-each loop would not work correctly because the collection is changing size at
the same time that the code is trying to loop

ArrayList<String> cars = new ArrayList<String>();

cars.add("Volvo");cars.add("BMW");cars.add("Ford");cars.add("Mazda");

<String> it = cars.iterator(); // Get the iterator

ArrayList<Integer> numbers = new ArrayList<Integer>();

numbers.add(12); numbers.add(8); numbers.add(2); numbers.add(23);

Iterator<Integer> it = numbers.iterator();

while(it.hasNext()) { i = it.next();

if(i < 10) {it.remove();} }

System.out.println(numbers);

*********************EXCEPTIONS(TRY AND CATCH)

*******TRY AND CATCH,FINALLY and THROW

TRY AND CATCH JAVA ON THIS AND IF IT FINDS ERROR ITS


GONNA GO TO CATCH AND GONNA RUN IT

FINALLY JAVA WILL RUN IT NO MATTER WHAT


THORW-> WE make our own custom error with various tyopes of
existing errors
ex=ArithmeticException, FileNotFoundException, ArrayIndexOutOfBoundsException, SecurityException

*****************FILE HANDLING

import java.io.File; // Import the File class

File myObj = new File("filename.txt"); // Specify the filename

CREARTING A FILE

File myObj = new File("filename.txt");

if (myObj.createNewFile()) {System.out.println("File created: " + myObj.getName())

WRITING TO A FILE

FileWriter myWriter = new FileWriter("filename.txt");

myWriter.write("Files in Java might be tricky, but it is fun enough!");

myWriter.close();

try {

File myObj = new File("filename.txt");


READING THE FILE

Scanner myReader = new Scanner(myObj);

while (myReader.hasNextLine()) {

String data = myReader.nextLine();

System.out.println(data);

DELETING THE FILE

myReader.close();

File myObj = new File("filename.txt");

if (myObj.delete()) {

System.out.println("Deleted the file: " + myObj.getName());

KEYWORD ‘super’ used to refer parent class obj(used in inheritance)

Say if a class N extends M and they have same method ONO() where
their body is different. So an obj of N with keyword super will
implement method body in M.

Encapsulation ; public , private, protected

Method overriding; We have a method with same name in a class


and in its subclass(the one that extends class) and an object
created otta subclass will initialize the body of method in
subclass,not in the class.

Interfaces; almost like an abstract class i.e have a method with


empty body.

Public interface name{

Void namemethod () ; }

Public class wolf implements name {


Public Void name(){ //code }

That’s how u create an interface and use it in class

Class name implements interface1,interface2 // having two


interfaces

Methods in interface can have body by adding ‘default’ before


method type.(feature of java 8 )We can even override those
methods.

Static and private method in interfaces; can have a body

Public interface Animal()

{ Static void talk(){ System.out.println(“ soy hablar ”);

Private void scream(){ System.out.println(“AAAaah”); }

Class next{ Main() { Animal.talk(); Animal.scream(); } }

Exception handling ;We do it so that we can handle error manually


rather than by default handler

Keywords;Try, Catch, Throw, Throws AND Finally


int c ;
try{
int bob = 89; c= bob/0;}
catch(ArithmaticeException e){ c=o; } // exceptions are nothing but objects in java

as u see we are gonna get an arithmetic exc

There’re many exc types in java;so google search it


method () throws exceptionName {}

that’s how you use throws keyword


MULTITHREADED PROGRAMMING

Multithreads means running different things in a programs at same


time ex; watching video on yt and also searching for other video.

Methods; getName , getPriority , isAlive , join , run , sleep , start


public class Main(){
public static void main(String[], args) {
Thread myThread = Thread.currentThread();
myThread.setName("name of thread");
myThread.setPriority(3);//main method usually have priority 5
Thread.sleep(mills 1000); // means thread sleeps for 1sec

BELOW SHOWS THAT WE NEED TO USE THE THREAD OBJ TO INITIALIZE A THREAD

class MyThread implements Runnable{


Thread t;
MyThread(){ t = new Thread(target this,name "my thread"); // this means t meantioned above
System.out.println("Child thread created"); }
@override
public void run(){ // this will run when MyThread is called
try { for(int i =5;i>0;i--) System.out.println(i);
Thread.sleep(mills 1000)}
catch(InterreptedException e){ System.out.println(e);}}
public class Main(){public static void main(String[], args) {
MyThread bear= new MyThread();
bear.t.start(); // WE ARE USING OBJ OF THREAD TO INITIALIZE IT
try{ for(int i =5;i>0;i--)System.out.println(i);Thread.sleep(mills 1000)} // TWO DIFFERENT THREAD WILL RUN IN OUR PROGRAM
catch(InterreptedException e){ystem.out.println(e); }}}

BELOW IS ALT TO ABOVE CODE

class MyThread extends Thread{


MyThread(){super(name " my thread ");}}
public class Main(){public static void main(String[], args) {
MyThread bear= new MyThread();
bear.start();
try{ for(int i =5;i>0;i--)
System.out.println(i);Thread.sleep(mills 1000)}
catch(InterreptedException e){
System.out.println(e); }}

Creating multiple threads in a class

class MyThread implements Runnable{


String name; Thread t;
MyThread(String name){
this.name= name;
t = new Thread( target this, name);
}
public void run(){ // this will run when MyThread is called
try { for(int i =5;i>0;i--) System.out.println(i);
Thread.sleep(mills 1000)}
catch(InterreptedException e){ System.out.println(e);}

}
main(){
MyThread thread1 = new MyThread(name "Thread1 "); thread1.t.start();
MyThread thread2 = new MyThread(name "Thread2"); thread2.t.start();
MyThread thread3 = new MyThread(name "Thread3"); thread3.t.start();
}

isAlive() and join()


class MyThread implements Runnable{
String name;
Thread t;
MyThread(String name){
this.name=name;
t = new Thread(target this, name );
}
public void run(){ // this will run when MyThread is called
try { for(int i =5;i>0;i--) System.out.println(i);
Thread.sleep(mills 1000)}
catch(InterreptedException e){ System.out.println(e);}
}
main(){
MyThread thread1 = new MyThread(name "Thread1 ");
MyThread thread2 = new MyThread(name "Thread2");
MyThread thread3 = new MyThread(name "Thread3");
thread1.t.isAlive(); /// WILL PRINT FALSE
thread1.t.start()
try{thread1.t.join()}
catch(InterreptedException e){ System.out.println(e);}
thread1.t.isAlive(); // WILL PRINT TRUE
thread2.t.start(); // so what join does is is will let thread1 run
thread3.t.start(); // completely and then thread2 will come in action
}

So what isAlive() returns is a Boolean and join() don’t let others


threads to join unless the thread it’s joined to is finished with
beeswax.

Synchronized Threads
THREADS THEORY

TWO WAYS TO DO THREADING IN JAVA

1)Create a class and extend in to Thread. Override run() method.


Then in main create object of that class and invoke start() method
public class MyThread extends Thread{ public void run(){Sy .. //code} }

public static void main(String[] args){ MyThread newobj = new MyThread(); newobj.start(); }

2)Create a class and implements Runnable interface(in JAVA we


cant extend a class to 2-3 other classes but we can implement 2-3
interfaces to it so this can be useful in that situation) then override
run() method in that class. Create an object in main class and
invoke start() .
public class MyThread implements Runnable { public void run(){// code } }

public static void main (String[] args){ Thread t = new Thread(new MyThread()); t.start();}

DEMON THREAD IS THE THREAD THAT GETS EXECUTED ALONG


WITH MAIN

MUTLITHREADING –

class Printer{

synchronized void printDocument(int m, String docName) {


for(int i= 0;i<=10;i++) {
try { Thread.sleep(500); }
catch( InterruptedException e) { }
System.out.println(">> Printing " + docName+ " " + i);
}
}
}

class MyThread extends Thread{

Printer pRef;
MyThread(Printer p){
pRef =p;
}
@Override
public void run() {
pRef.printDocument(10, "Alice");
}
}
class YourThread extends Thread{

Printer pRef;
YourThread(Printer p){
pRef =p;
}
@Override
public void run() {
synchronized(pRef) {
pRef.printDocument(10, "Chris");
}
}

Main()=

System.out.println("START");

Printer printer = new Printer();


printer.printDocument(10, "II.pdf");

MyThread mRef = new MyThread(printer);


mRef.start();
//try { mRef.join(); }
//catch(InterruptedException e) {}

YourThread yRef = new YourThread(printer);


yRef.start();
System.out.println("END");

So whats all these pieces of words huh!!

So we made a class called Printer and gave it a method call printDocument. Then we
made two child classes of class Thread(i.e basically thread classes) and filled
them with constructors that take in a Printer object as arg.For each thread class
we made a Printer object that takes the given parameter to the constructor then
implies that in the run() method.In run() method we are impling the printDocument
method using this given parameter.

Now in main we made a Printer object and objects of other two classes.While making
so we gave in the Printer object as the parameter for the constructor of those two
classes. Then we implemented start() method for those two objects of thread class
to make them run but we got jumbled output so we used something called join()
method // NOTE; use try catch for join(),sleep() and so on // This will help in
synchronization or else go to the Printer class and put ‘ synchronized ‘ that will
do same.

THEAD POOL –
LAMBA EXPRESSION IN JAVA

It’s Functional programming in java.

It’s parameter -> expression body

FUNTIONALAL INTERFACE

ITS AN INTERFACE THAT CONTAINS ONLY ONE ABSTRACT METHOD

Runnable , ActionListner, Comparable

@FunctionalInterface // optional to add


interface Cab // When an interface hac exactly 1 abstract method its called
//as Functional Interface
{

void bookCab(); // by default public abstract void bookCab();


}

MAIN=

// USING LAMBA EXP FOR ABOVE


Cab cab = ()-> {
System.out.println("Hey o ");
};
cab.bookCab();

LAMBA PARAMETERS

ZERO ()-> System.out.println(“Sd”);

ONE (param)-> System.out.println(“sdf”+ param);

MULTIPLE (p1 p3 )-> System.out.println(p1+p2);

LAMBA WITH RETURN TYPE

interface cab2 {
double bookCab(String source,String destination);

MAIN=

cab2 cabby = (source,destination)-> {

System.out.println("sd"+ source + destination);


return 222.2;
} ;
double fare = cabby.bookCab("s", "Df" );
System.out.print(fare);
LAMBA AS AN OBJECT

INTERFACE = public interface LambdaComparator{

Public boolean compare(int a,int b); }

IMPLEMENTING CLASS = LambdaComparator myComparator = (a,b)-> return a>b;

boolean result = myComparator.compare(3,4);

LAMBA VARIABLE CAPTURE

LOCAL String str =”sdf”;

MyLambda dis = (chars)->{

Return str + new String(chars); };

STATIC

INSTANCE private String st = “sdf”;

Public void attach (Lam) {

public class Al22 {

int instanceVar =11;


static int sVar = 112;

public static void main(String[] args) {

OUTSIDE MAIN =

cab2 cabby = (source,destination)-> {


int localVar = 112; // LOCAL VARIABLE
System.out.println("sd"+ source + destination);
System.out.println(instanceVar + Al22.sVar + localVar );
return 222.2;
};

METHOD REFERENCES AS LAMBDAS


Easier form of lambda exps

Below is the example of 3 ways of ref to methods

interface calculator{
void add (int a ,int b);
}

class calc{
public static void addsomething(int a,int b){
System.out.println(a+b);
}

public void adddda(int a,int b){


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

interface Messanger{
Message getMessage(String mgs);
}

class Message{
Message(String msg){
System.out.println(msg);
}
}

main=

// Ref to a static method


calculator cref = calc::addsomething; // Mthod ref
cref.add(4,2);

// Ref to non static method or instance method


calc cal = new calc();
calculator cref = cal::adddda; // Method ref
cref.add(45,5);

//Ref to a constructor
Messanger mref = Message::new; //Method ref
mref.getMessage("sdf");
PARSING XML USING DOM,SAX AND StAX PARSER IN JAVA

XML =

// java.io.* // have everything for input output

In above we made a file obj first giving the path inside the
constructor. Then we made a method cuz that’s a good
programming practise and also bcuz of that we can use that method
next time for other file obj as well. Now in method we supplied the
file object as parameter as we wonna work with that and we wrote
a try catch thing cuz this process gives errors by def in java. Now
we made an obj of PrintWriter out of try catch as we would have to
use it in finally as well(since we wonna close the file ). In try we
used this obj and passed the method parameter into the PrintWriter
constructor(which is gonna work on the original file we wonna workl
with). El fin.
This is reading from a file.We use scanner.

NOW BELOW SHOWS USING A FILEWRITER TO DO THE JOB


WRITE TO FILE WAY

SERIALIZATION AND DESERIALIZATION

Process of converting objects into binary data and sending it to


other computer is serialization.
FILES

Don’t make this file in src folder,make it in root folder


GENERICS

7;30-8;20 we gotta see

List,queue,set-hash ,enums allthat + generics


Generic detailed explanation

Part 1 expl

Ex1 class gen <type> {


type var;
void setvar(type a) {
this.var= a;
}
MAIN =
gen f = new gen();
f.setvar(4);
f.setvar("ef");
System.out.println(f.var);

Ex 2 class gen <type> {


type var;
public gen(type string) {
// TODO Auto-generated constructor stub
this.var= string;
}
public gen() {
// TODO Auto-generated constructor stub
}
void setvar(type a) {
this.var= a;

Main = gen<String> ad = new gen<String>("sd");System.out.println(ad.var);


gen<Double> ads = new gen<Double>(1.5); System.out.println(ads.var);

Part 2 explanation

class generic<T1,T2>{

int val;
T1 a;
T2 b;
generic(T1 a,T2 b){
this.a=a;
this.b=b;
System.out.println(a +" " + b);
}

MAIN =

generic as = new generic("asd",5);

BUT FIRST LOOK INTO TYPECASTING

Its converting one data type into other data type


Types= 1) implicit; automatically performed by compiler.

Ex int a 19; double s a;

2) explicit;

EX double a 34.34; int b (int) a; means double got converted into int

TYPE WRAPPERS

1st way = Character cs = new Character('c');

2nd way = Character css = Character.valueOf('c');

Double sdsd = Double.valueOf(4.4);


double sda = sdsd.doubleValue();

AUTOBOXING

Auto conversation of primitive into object

ENUMS

Its a special type of class that lets u make a new data type and
then you can decide what data that data type will take(we don’t
have to deal with new keyword) enums can inherit and extends.

enum Days{
Monday, Tuedays, WED // they are static and final and constant by default}
MAIN =

Days days = Days.Monday;


// now we have a variable made called days

Days ar[] = Days.values(); // fill ar[] with all Days value


XML - Designed to store and transport data.

Rukes= 1] considers space as data

2] xml tags are case sensitive 3] close tag and open tag bt exist.

//FINDING STUFF IN STRING


// endsWith() n startsWith() gives what it says
for string
// indexOf(' ') used to find characters in
strings
// concat() joins two strings to a one word
// replace('a','ad') replaces in string

//RECURSION
// ITS A METHOD THAT CALLS ITSELF
/* PUBLIC STATIC LONG FACT(INT A) {
IF(A<=1)
RETURN 1;
ELSE RETURN A*FACT(A-1);
}
COLLECTION ;

ITERATOR

// Iterator<String> i = l1.iterator(); ( l1 name of list )


//Iterator = goes through each list item by item

// i.hasNext() , i.next() , i.remove()


/*

List<String> la = new ArrayList< String>();


List<String> lb = new ArrayList< String>();
la.add("AS"); la.add("ASA") ; la.add("ASAS");
lb.add("df"); la.add("ASAS"); lb.add("fe");

editlist(la,lb);

public static void editlist (List<String> lla,List<String> llb) {


Iterator<String> it = lla.iterator();
while(it.hasNext()) {
if(llb.contains(it.next()))
it.remove(); //

LINKED LIST

String[] things = {"a","as","asd"}; //


list1.add(list2)
// will give list1 all
list2 data
List<String> l1 = new LinkedList<String>();
for(String c : things)
l1.add(c);
//.subList(from,to) seprates a chunk
in a list
*/ // .clear() deletes list

/* //ARRAY TO LIST AND


EITHER

String[] stuff = {"a","d","f","g"};


LinkedList<String> list = new LinkedList<String>(Arrays.asList(stuff));

//we just made an array into


a list
list.add("pimp");
list.addFirst("I'M ADDED AT INDEX 0"); // LOOK AT THIS DAMN GAL

stuff = list.toArray(new String(list.size()));


// conv list to array
// LIST METHODS

String[] crap = {"a","d","f"};


List<String> lst = Arrays.asList(crap);
Collections.sort(lst); // sorted our list in alphabetical
order
System.out.printf(null, lst); // we gave a list as a string

Collections.sort(lst, Collections.reverseOrder()); // will sort list in reverse


order

Character[] ra = {'a','s', 'f', 'g' };


List<Character> lst = Arrays.asList(ra);

// Collections ; rverse and pritn opt


the lsut
Collections.reverse(lst);

// fill collection wtih crap


Collection.fill(l,'X');

// METHOD addAll()
// adds one collection data into other collection
// this is ognan add elements of stuff to list2
//Collections.addAll(list2, stuff);

//FREQUENCY
//frequency gives output of how many times an element appear in
list
// Collections.frequency(list, "FI");

// DISJOINT
// boolean t = Collections.disjoint(list, lst);
// True is no items in common
// False if items in common
*/

STACKS

// DATA STRUCTURE => STACKS ;


//PUSH AND POP(take sometig off it)
/*
Stack<String> st = new Stack<String>();
st.push("BOT");
printStack(st);
st.push("sd");
printStack(st);
st.push("sd3");
printStack(st);
// printStack is a method we made
st.pop();
printStack(st); _ first to pop
st.pop(); _
printStack(st); _ last to pop
st.pop();
printStack(st);

private static void printStack(Stack<String> a) {


if(a.isEmpty())
System.out.println("Nothing in stack");
else
System.out.printf("Top", a);
}

// DATA STRUCTURE = QUEUE

PriorityQueue<String> q = new PriorityQueue<String>();

q.offer("sd");
q.offer("asd");
q.offer("gd");
System.out.printf("%s", q); // prints whole queue at once

System.out.printf("%s",q.peek()); // output = sd; it has high


priority

q.poll(); // removes high priority


element

// Set = Collection that doesn't have


duplicate
//elements in it

// 1) HashSet
String[] stuff = {"a","s","a"};
List<String> li = Arrays.asList(stuff); // we made array into list n got it
System.out.printf("%s", li); // print

Set<String> set = new HashSet<String>(li); // we made set obj


System.out.printf("%s", set); // set eliminated 2nd a in list
CALENDAR CLASS

Its an abstract class so cant make obj so create an instance of it.


Calendar c = Calendar.getInstance();

Methods c.get(Calendar.YEAR) and many more

RANDOM CLASS

Able to generate random data type


Random r = new Random();
System.out.println(r.nextInt()); will give random number

TIMER AND TIMER TASK

MAIN=

HASHMAPS = KEY/DATA

HashMap<String, Integer > pn = new HashMap<>();


pn.put("Bob",52232);
System.out.println(pn.get("Bob"));

Special loop for( Map.Entry<String, Integer> set : pn.entrySet() ) {


System.out.println(set.getValue());

ITERATOR AND LISTITERATOR- used to loop over a list or a collection

You might also like