0% found this document useful (0 votes)
4 views29 pages

Java Programming Concepts Explained

This document provides summaries of key Java concepts: 1. Constructors are used to initialize objects and have the same name as the class. Parameters can be passed to a constructor to set values. 2. Access modifiers like final, static, and abstract can be applied to attributes, methods, and classes. Final prevents modification, static associates with a class not object, and abstract requires inheritance. 3. Packages organize classes and methods. Interfaces define methods without bodies that classes can implement. Inner classes are defined within other classes. 4. Collections like ArrayLists, LinkedLists, HashMaps, and HashSets store and manipulate objects. Common operations on collections include adding, removing, and iterating over

Uploaded by

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

Java Programming Concepts Explained

This document provides summaries of key Java concepts: 1. Constructors are used to initialize objects and have the same name as the class. Parameters can be passed to a constructor to set values. 2. Access modifiers like final, static, and abstract can be applied to attributes, methods, and classes. Final prevents modification, static associates with a class not object, and abstract requires inheritance. 3. Packages organize classes and methods. Interfaces define methods without bodies that classes can implement. Inner classes are defined within other classes. 4. Collections like ArrayLists, LinkedLists, HashMaps, and HashSets store and manipulate objects. Common operations on collections include adding, removing, and iterating over

Uploaded by

Shahzaad Vinad
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

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 [Link] 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 [Link]; // import [Link].*;

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

Then we can excess the object inside inner class by using


[Link] name = new [Link]();
class OuterClass {

int x = 10;

private class InnerClass {

int y = 5; }

public class Main {

public static void main(String[] args) {

OuterClass myOuter = new OuterClass();[Link] myInner = [Link] InnerClass();

[Link](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() {

[Link]("The pig says: wee wee");}

public void sleep() {[Link]("Zzz"); } }


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

Stuffs that can’t be [Link] 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 = [Link]; [Link](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 = [Link];

switch(myVar) {

case LOW: [Link]("Low level");break;

case MEDIUM: [Link]("Medium level");break;

case HIGH: [Link]("High level");break;

}}}

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

enum moods{

ANGRY; HAPPY; BLUE; }

Main(){

For(moods Var : [Link]() ) { /// body } }

********************TIME IN JAVA
Import [Link].*; // package

Or alot of classes =>


import [Link]; // Import the LocalDateTime class

import [Link]; // Import the DateTimeFormatter class

public class Main {

public static void main(String[] args) {

LocalDateTime myDateObj = [Link]();[Link]("Before formatting: " + myDateObj);

DateTimeFormatter myFormatObj = [Link]("dd-MM-yyyy HH:mm:ss");

String formattedDate = [Link](myFormatObj); [Link]("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 [Link]; import [Link];

[Link](cars); THIS BAD BOY SORTS THE ARRAYLIST CALLED cars

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

[Link](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 [Link]; // import the HashMap class

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

[Link]("England", "London");[Link]("England");[Link]("England");

[Link](); [Link]();

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

******************HASHSETS
import [Link]; // Import the HashSet class

HashSet<String> cars = new HashSet<String>()[Link]("Volvo");

[Link]("Mazda"); [Link]("Volvo"); [Link]();

for (String i : cars) {

[Link](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>();

[Link]("Volvo");[Link]("BMW");[Link]("Ford");[Link]("Mazda");

<String> it = [Link](); // Get the iterator

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

[Link](12); [Link](8); [Link](2); [Link](23);

Iterator<Integer> it = [Link]();

while([Link]()) { i = [Link]();

if(i < 10) {[Link]();} }

[Link](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 [Link]; // Import the File class

File myObj = new File("[Link]"); // Specify the filename

CREARTING A FILE

File myObj = new File("[Link]");

if ([Link]()) {[Link]("File created: " + [Link]())

WRITING TO A FILE

FileWriter myWriter = new FileWriter("[Link]");

[Link]("Files in Java might be tricky, but it is fun enough!");

[Link]();

try {

File myObj = new File("[Link]");


READING THE FILE

Scanner myReader = new Scanner(myObj);

while ([Link]()) {

String data = [Link]();

[Link](data);

DELETING THE FILE

[Link]();

File myObj = new File("[Link]");

if ([Link]()) {

[Link]("Deleted the file: " + [Link]());

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(){ [Link](“ soy hablar ”);

Private void scream(){ [Link](“AAAaah”); }

Class next{ Main() { [Link](); [Link](); } }

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 = [Link]();
[Link]("name of thread");
[Link](3);//main method usually have priority 5
[Link](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
[Link]("Child thread created"); }
@override
public void run(){ // this will run when MyThread is called
try { for(int i =5;i>0;i--) [Link](i);
[Link](mills 1000)}
catch(InterreptedException e){ [Link](e);}}
public class Main(){public static void main(String[], args) {
MyThread bear= new MyThread();
[Link](); // WE ARE USING OBJ OF THREAD TO INITIALIZE IT
try{ for(int i =5;i>0;i--)[Link](i);[Link](mills 1000)} // TWO DIFFERENT THREAD WILL RUN IN OUR PROGRAM
catch(InterreptedException e){[Link](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();
[Link]();
try{ for(int i =5;i>0;i--)
[Link](i);[Link](mills 1000)}
catch(InterreptedException e){
[Link](e); }}

Creating multiple threads in a class

class MyThread implements Runnable{


String name; Thread t;
MyThread(String name){
[Link]= 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--) [Link](i);
[Link](mills 1000)}
catch(InterreptedException e){ [Link](e);}

}
main(){
MyThread thread1 = new MyThread(name "Thread1 "); [Link]();
MyThread thread2 = new MyThread(name "Thread2"); [Link]();
MyThread thread3 = new MyThread(name "Thread3"); [Link]();
}

isAlive() and join()


class MyThread implements Runnable{
String name;
Thread t;
MyThread(String name){
[Link]=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--) [Link](i);
[Link](mills 1000)}
catch(InterreptedException e){ [Link](e);}
}
main(){
MyThread thread1 = new MyThread(name "Thread1 ");
MyThread thread2 = new MyThread(name "Thread2");
MyThread thread3 = new MyThread(name "Thread3");
[Link](); /// WILL PRINT FALSE
[Link]()
try{[Link]()}
catch(InterreptedException e){ [Link](e);}
[Link](); // WILL PRINT TRUE
[Link](); // so what join does is is will let thread1 run
[Link](); // 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(); [Link](); }

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()); [Link]();}

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 { [Link](500); }
catch( InterruptedException e) { }
[Link](">> Printing " + docName+ " " + i);
}
}
}

class MyThread extends Thread{

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

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

Main()=

[Link]("START");

Printer printer = new Printer();


[Link](10, "[Link]");

MyThread mRef = new MyThread(printer);


[Link]();
//try { [Link](); }
//catch(InterruptedException e) {}

YourThread yRef = new YourThread(printer);


[Link]();
[Link]("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 [Link] each thread class
we made a Printer object that takes the given parameter to the constructor then
implies that in the run() [Link] 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 [Link] 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 = ()-> {
[Link]("Hey o ");
};
[Link]();

LAMBA PARAMETERS

ZERO ()-> [Link](“Sd”);

ONE (param)-> [Link](“sdf”+ param);

MULTIPLE (p1 p3 )-> [Link](p1+p2);

LAMBA WITH RETURN TYPE

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

MAIN=

cab2 cabby = (source,destination)-> {

[Link]("sd"+ source + destination);


return 222.2;
} ;
double fare = [Link]("s", "Df" );
[Link](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 = [Link](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
[Link]("sd"+ source + destination);
[Link](instanceVar + [Link] + 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){
[Link](a+b);
}

public void adddda(int a,int b){


[Link](a+b);
}

interface Messanger{
Message getMessage(String mgs);
}

class Message{
Message(String msg){
[Link](msg);
}
}

main=

// Ref to a static method


calculator cref = calc::addsomething; // Mthod ref
[Link](4,2);

// Ref to non static method or instance method


calc cal = new calc();
calculator cref = cal::adddda; // Method ref
[Link](45,5);

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

XML =

// [Link].* // 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 [Link] 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) {
[Link]= a;
}
MAIN =
gen f = new gen();
[Link](4);
[Link]("ef");
[Link]([Link]);

Ex 2 class gen <type> {


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

Main = gen<String> ad = new gen<String>("sd");[Link]([Link]);


gen<Double> ads = new gen<Double>(1.5); [Link]([Link]);

Part 2 explanation

class generic<T1,T2>{

int val;
T1 a;
T2 b;
generic(T1 a,T2 b){
this.a=a;
this.b=b;
[Link](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 = [Link]('c');

Double sdsd = [Link](4.4);


double sda = [Link]();

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 = [Link];


// now we have a variable made called days

Days ar[] = [Link](); // 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 = [Link](); ( l1 name of list )


//Iterator = goes through each list item by item

// [Link]() , [Link]() , [Link]()


/*

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


List<String> lb = new ArrayList< String>();
[Link]("AS"); [Link]("ASA") ; [Link]("ASAS");
[Link]("df"); [Link]("ASAS"); [Link]("fe");

editlist(la,lb);

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


Iterator<String> it = [Link]();
while([Link]()) {
if([Link]([Link]()))
[Link](); //

LINKED LIST

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


[Link](list2)
// will give list1 all
list2 data
List<String> l1 = new LinkedList<String>();
for(String c : things)
[Link](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>([Link](stuff));

//we just made an array into


a list
[Link]("pimp");
[Link]("I'M ADDED AT INDEX 0"); // LOOK AT THIS DAMN GAL

stuff = [Link](new String([Link]()));


// conv list to array
// LIST METHODS

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


List<String> lst = [Link](crap);
[Link](lst); // sorted our list in alphabetical
order
[Link](null, lst); // we gave a list as a string

[Link](lst, [Link]()); // will sort list in reverse


order

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


List<Character> lst = [Link](ra);

// Collections ; rverse and pritn opt


the lsut
[Link](lst);

// fill collection wtih crap


[Link](l,'X');

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

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

// DISJOINT
// boolean t = [Link](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>();
[Link]("BOT");
printStack(st);
[Link]("sd");
printStack(st);
[Link]("sd3");
printStack(st);
// printStack is a method we made
[Link]();
printStack(st); _ first to pop
[Link](); _
printStack(st); _ last to pop
[Link]();
printStack(st);

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


if([Link]())
[Link]("Nothing in stack");
else
[Link]("Top", a);
}

// DATA STRUCTURE = QUEUE

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

[Link]("sd");
[Link]("asd");
[Link]("gd");
[Link]("%s", q); // prints whole queue at once

[Link]("%s",[Link]()); // output = sd; it has high


priority

[Link](); // removes high priority


element

// Set = Collection that doesn't have


duplicate
//elements in it

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

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


[Link]("%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 = [Link]();

Methods [Link]([Link]) and many more

RANDOM CLASS

Able to generate random data type


Random r = new Random();
[Link]([Link]()); will give random number

TIMER AND TIMER TASK

MAIN=

HASHMAPS = KEY/DATA

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


[Link]("Bob",52232);
[Link]([Link]("Bob"));

Special loop for( [Link]<String, Integer> set : [Link]() ) {


[Link]([Link]());

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

Common questions

Powered by AI

In Java, threads can be created by either extending the Thread class or implementing the Runnable interface. Extending the Thread class means subclassing it, which can be simpler as it allows direct access to thread methods and properties; however, it prevents the subclass from extending any other class. On the other hand, implementing Runnable is a more flexible approach as it allows the class to extend other classes as well. The Runnable method encapsulates the thread's running behavior in a separated run() method, promoting better object-oriented design and separation of concerns, though it might require additional setup (i.e., needing a Thread object to run the Runnable).

The 'synchronized' keyword in Java is used to lock access to objects or methods, ensuring that only one thread can execute a synchronized method or block on the same object at a time. This is critical for maintaining consistency when multiple threads access shared resources, preventing thread interference and memory consistency errors. When two threads access the 'printDocument' method of the 'Printer' class concurrently, synchronizing this method ensures that no two threads can execute the method simultaneously, thus maintaining the integrity of printed documents .

Exceptions in Java can be handled using try-catch blocks to maintain program stability by preventing unhandled exceptions from crashing the program. For example, during arithmetic operations like division, where division by zero is possible, one might use a try-catch block to catch an ArithmeticException. Consider the code: 'try { int c = bob / 0; } catch (ArithmeticException e) { c = 0; }'. Here, if division by zero occurs, the catch block assigns zero to 'c', allowing the program to continue executing without interruption .

Java's generics enable types (classes and interfaces) to be parameters when defining classes, interfaces, and methods. The primary advantage of using generics is type safety, which allows errors to be detected at compile time rather than at runtime. For example, when using generics with a List, specifying 'List<String>' means the list can only contain String objects, reducing the risk of ClassCastException that would occur if non-string objects were placed in the list inadvertently. Generics ensure that the code adheres strictly to the type constraints, making it safer and less prone to runtime errors related to incorrect object types .

Method references provide a way of simplifying the syntax of lambda expressions by referring to existing methods by name. There are four types of method references in Java: reference to a static method, reference to an instance method of a particular object, reference to an instance method of an arbitrary object of a particular type, and reference to a constructor. For instance, 'String::valueOf' is a static method reference, while 'instance::methodName' refers to an instance method on a specific object, and 'Class::new' refers to a constructor. These references allow for a cleaner and easier-to-read syntax when using functional interfaces .

The 'super' keyword in Java is used to refer to the parent class's object, allowing a subclass to call methods from its superclass even when it has overridden those methods. For instance, if class N extends class M and both classes have a method called ONO(), an object of class N using 'super.ONO()' will execute the ONO() method defined in class M instead of its own version. This is useful for accessing overridden methods from a parent class when dealing with inheritance .

Interfaces offer more flexibility than abstract classes because while a class can only extend one abstract class due to Java's single inheritance model, it can implement multiple interfaces, allowing for a form of multiple inheritance. After Java 8, interfaces can also have default methods with complete implementations, which can be overridden by implementing classes. Interfaces can have static and private methods defined within them as well. This flexibility allows developers to create more modular and versatile code structures .

The 'isAlive' method in Java is used to check if a thread is still running or not, returning true if the thread has not terminated yet. This is useful for monitoring the state of a thread. When used together with the 'join' method, which causes the calling thread to wait for this thread to die, they provide a way to ensure a sequential thread execution order. The 'join' method ensures that a thread completes its execution before another thread can continue, thus providing a mechanism to coordinate thread execution timing for complex multithreading requirements .

Lambda expressions in Java provide a concise way to implement single-method interfaces using expressions, significantly reducing boilerplate code and increasing code readability and maintainability. However, the compact nature of lambda expressions can lead to potential pitfalls. The reduced verbosity can sometimes obscure control flow, making it harder to trace program logic during debugging. Debugging tools may not always clearly represent lambda expressions, posing challenges in identifying and resolving issues. Additionally, excessive use of lambdas may obscure the program's architecture and logic when not documented properly .

A Functional Interface in Java is an interface that contains exactly one abstract method. These are pivotal to the implementation of lambda expressions, which provide a clear and concise syntax to pass methods as arguments or to be used to define inline implementations without anonymous inner classes. It's most appropriate in scenarios where a single functionality is to be implemented, like event handling, or where instances of functional interfaces can be passed as parameters, providing more functional and clean code .

You might also like