Java Notes
Java Notes
Java is
platform-independent, object-oriented and secure. It is a high-level language which is
first compiled into a binary byte-code and this byte-code is run on the Java Virtual
Machine, a software-based interpreter. Source code >> Java Compiler >> Byte Code >>
Java Interpreter >> Native Code To convert the java file to Java byte code using the
Java Compiler, run
javac <[Link]>
This will produce a .class file which contains machine-readable instructions that
can be executed by JVM. To execute the compiled file,
java <filename>
8. Conditionals:
7. Random Numbers 9. Switch Statements
if...else
19. Method Overloading 20. printf method 21. The final keyword
25. Constructor
26. toString 27. Array of Objects
Overloading
38. Runtime
37. Polymorphism 39. Exception Handling
Polymorphism
55. Multithreading
JDK
Java Development Kit (JDK) is a software development kit for Java. It contains the
basic tools and libraries required in Java Programming. There are 7 main programs in
JDK:
Programs Description
APIs
Application Programming Interface in JDK enables developers to make various applets
and applications. It contains 9 packages:
Packages Description
[Link] Built-In Data Structures like Vector, Stack, Dictionary, Hash etc.
Primitive - 8 types
Reference
Identifiers
Identifiers are names given to various program elements like variables, classes,
constants, methods etc. It may contain letters, numbers and '_'. The first character
cannot be a number. Identifiers are case sensitive.
Scanner
To receive input from the user.
import [Link];
---
Scanner sc = new Scanner([Link]);
String name = [Link]();
Math Methods
Function Use
Random Numbers
To use random numbers, we need to import the random class
import [Link];
Conditionals: if...else
if (condition1) {
statements;
...
} else if (condition2) {
statements;
...
} else {
statements;
...
}
Switch Statements
Switch is a statement that allows a variable to be tested for equality against a list
of values.
switch (condition) {
case value1:
statements;
...
break;
case value2:
statements;
...
break;
...
default:
statements;
break;
}
Logical Operators
Logical operators are used to connect two or more expressions.
while (condition) {
statements;
...
}
do {
statements;
...
} while (condition);
Arrays
Array is a finite collection of homogeneous data elements.
1. Declaration
<type> <arrayName>[];
or
<type>[] <arrayName>;
2. Allocation of memory
Or we can do both by
<arrayName>[index] = value;
Or just do
String Methods
Function Use
[Link](str2),
Compare two strings
[Link](str2)
[Link](),
Changes the case
[Link]()
Wrapper Classes
Wrapper Classes provide a way to convert primitive data types into an object
(reference datatype).
Primitive Wrapper
int Integer
boolean Boolean
char Character
double Double
Strings are reference datatypes. Reference datatypes are naturally slower than
primitive ones, but there are several useful methods associated with reference
datatypes.
Boolean b = true;
import [Link];
[Link](item);
To retrieve elements, do
[Link](index);
[Link](arraylist_name);
for-each loop
Also known as an advanced for loop, for-each loop is used to iterate through all the
elements in a collection. for-each loops can be written in less steps and are more
readable, but less flexible.
Methods
A method is a collection of statements grouped together to perform a certain task.
Method Signature: Part of the method declaration including method name and
parameter list.
Access Specifier: Specifies the access type/ visibility of the method.
Return Type: The datatype of the value that the method returns.
We use the public keyword so that the method is identifiable to the JVM. Static
Methods, made using the keyword static , are methods which invokes without creating
an object. The main method also accepts data from the user. It accepts a string array,
which is used to hold the command line arguments. The String[] args parameter is used
for this purpose.
Parameters Arguments
Method Overloading
Overloaded Methods are methods with the same name, having different parameters. The
methods must have different Method Signatures.
void f(int n) {
...
}
void f(float f) {
...
}
If we call the function f using an argument that is neither int nor float ,
automatic type promotion will be applied. Thus, if we pass a character as an
argument, a the function with int argument will be called.
printf method
printf() is an optional method to control, format and display text. It takes two
arguments:
A format string
An object, variable or value
The format string contains a format specifier, starting with a % which tells where
the value should appear.
The format specifier formats the value and inserts it into the format string. The
structure of the format specifier is
The width field field sets the minimum number of characters to be written as
output.
[Link]("Hello%10s", "world");
↑
Inserts atleast 10 characters at this position
Precision sets the number of digits of precision when outputing floating point
values.
1. -: left-justify
2. +: include sign in the output for numerical values
3. 0: add zero padding to numerics
4. ,: comma grouping separator
Objects
An object is an instance of a class. Any entity with a state or behavior could be an
object. A class may contain attributes and methods. Objects can be physical or
logical. A collection of objects / a blueprint from which we can create an object, is
called a class . It is a logical entity
Constructors
Constructor is a special method that is called when a constructor is instantiated. A
constructor can be created by making a function with the same name as that of the
class.
class Human {
String name;
int age;
The current object can be referred inside the class using the this keyword.
Scope
A variable is said to be
Constructor Overloading
Constructor overloading is done by creating different constructors with the same name
within a class, but with different parameters. Each constructor must have their own
unique instances.
class Addition {
Addition(int a, int b) {
[Link](a + b);
}
Addition(int a, int b, int c) {
[Link](a + b + c);
}
}
toString
toString() is a special method that returns a string that textually represents an
object. We use it implicitly while printing an object, or we can use it explicitly by
calling [Link]() . By default, it returns the memory location in which the
object is stored. We can override this method and display an object appropriately, by
returning a string.
class Time {
int hour;
int minute;
int second;
public String toString() {
return hour + ":" + minute + ":" + second;
}
Array of Objects
Normally arrays are created as
Static
A static method / variable is a method / variable that belongs to a class, rather than
an object.
class Planet {
static String myPlanet;
...
}
[Link]([Link]);
[Link]()
Inheritance
Inheritance is a mechanism in which one class acquires the properites and behaviours
of a parent object. The class which inherits the other class is called a Sub Class or
Child Class . The Super Class / Parent Class is the class from which a subclass
inherits the features.
Method Overriding
Method overriding is the specific implementation of a method by the child class which
has been declared by its parent class.
class Organism {
void move() {
[Link]("Move");
}
}
class Fish extends Organism {
@Override
void move() {
[Link]("Swim");
}
}
The method in the child class is called the overriding method, and the one in the
parent class is called the overriden method.
Super
The super keyword refers to the superclass / parent class of an object. This is
similar to this , which refers to the same class.
class Organism {
String name;
Organism(String name) {
[Link] = name;
}
}
Abstract Keyword
The abstract keyword can be applied to both classes and methods. An abstract class
cannot be instantiated, but its sub-classes can.
Without using a modifier, we cannot use the method in a different package by importing
it.
A class defined without public is available only to classes within the same package.
Encapsulation
Encapsulation is the process of wrapping code and data together into a single unit.
Encapsulation means hiding the attributes of a class, by making it private or
protected. These attributes can be accessed only by special methods called getters
and setters .
class Person {
private String name;
// Getter
public String getName() {
return name;
}
// Setter
public void setName(String name) {
[Link] = name;
}
}
Person(String name) {
[Link](name);
}
Copying Objects
If we have two objects
Car car1;
Car car2;
car1 = car2;
which is wrong, since now both the names car1 and car2 are refering to the same
object. Instead, we should create a copy method within our class.
public void copy(Car car) {
[Link]([Link]());
[Link]([Link]());
[Link](car2);
Copy Constructors
We can create copy constructors to copy one object to another during the creation of
an object, like
To do this, add another constructor (overloading) which does the copying at the
creation.
Car(Car car) {
[Link](car);
}
Interface
An interface is a template that can be applied to a class. The template specifies what
a class has / must do. This is similar to inheritance, but inheritance is limited to
one super-class, meanwhile classes can apply more than one interface.
interface Prey {
void flee();
}
interface Predator {
void hunt();
}
If one class inherits from another, an object of the child class can be seen as
the same datatype as the parent class's object.
All objects are children-classes of the Object class, hence they also identify
as an Object.
Runtime Polymorphism
Runtime / Dynamic Polymorphism is a process in which a call to an overridden method
is resolved at runtime rather than compile time.
Language myLang;
if (choice == 1)
myLang = new English();
else if (choice == 2)
myLang = new Malayalam();
and each of these objects may have overriden methods, which can be invoked according
to its datatype
[Link]();
Exception Handling
An exception is an unexpected event that occurs during the execution of a program
which disrupts the normal flow of instructions. Example of exceptions include
ArithmeticException, InputMismatchException etc. We need to gracefully handle these
exceptions, using the try and catch blocks.
try {
risky_statements;
} catch (ArithmeticException e) {
statements;
} catch (Exception e) {
statements;
} finally {
statements_to_always_execute;
File Class
A File is an abstract representation of a file and directory path names. We can
import it by
FileWriter
To write to a file, do
[Link]("Something to write");
Or to append, do
[Link]("Something to append");
FileReader
The FileReader object lets us read the contents of a file as a stream of characters.
read() returns an 'int' value which contains the byte value of the character
currently being read. When read() returns -1 , the file has no more content to read.
int data = [Link]();
while (data != -1) {
[Link]((char) data);
data = [Link]();
}
[Link]();
Nested Classes
A class which is declared inside another class is called a nested class . Nested
classes are used to group classes that belong together, increase encapsulation and
readability. There are four types of nested classes:
1. Static nested classes: A static nested class is a nested class that is declared
with the static keyword. It is associated with the outer class, but it does not
have access to the instance variables and methods of the outer class. It can be
accessed using the outer class name followed by the nested class name, like
[Link] .
3. Local classes: A local class is a nested class that is defined inside a block,
such as a method or a loop. It is only accessible within the block where it is
defined. Local classes can access the variables and parameters of the enclosing
block, but they must be declared as final or effectively final.
4. Anonymous classes: An anonymous class is a nested class that does not have a
name. It is defined and instantiated at the same time. Anonymous classes are
often used to implement interfaces or extend classes on the fly without
creating a separate named class.
class ParentClass {
...
class InnerClass {
...
}
static class StaticNestedClass {
...
}
}
Enumerations
An enum is a special datatype that allows a variable to be a set of predefined
constants. The enum has a list of constants, and we can use these constants to create
variables.
enum Level {
LOW,
MEDIUM,
HIGH
}
The values() method returns an array containing all of the values of the enum.
Generics
Generics allow types to be passed as parameters at compile time.
class Box<T> {
private T t;
void set(T t) {
this.t = t;
}
T get() {
return t;
}
}
Generic methods can only be used with Reference Types (Integer, Character
etc.).
Collections
The Collections class consists of static methods that operate on collections.
Collections are used to store, retrieve, manipulate and communicate aggregate data. It
contains polymorphic algorithms that operate on collections.
reverse(List<?> list) Reverses the order of the elements in the specified list.
swap(List<?> list, int Swaps the elements at the specified positions in the
i, int j) specified list.
max(Collection<? extends
Returns the maximum element of the given collection.
T> coll)
rotate(List<?> list, int Rotates the elements in the specified list by the specified
distance) distance.
fill(List<? super T> Replaces all of the elements of the specified list with the
list, T obj) specified element.
[Link](list);
Stack
A Stack is a collection of elements, with two main operations: push and pop . It
follows the Last In First Out (LIFO) principle.
Queue
A Queue is a collection of elements, with two main operations: enqueue and
dequeue . It follows the First In First Out (FIFO) principle.
LinkedList
A LinkedList is a collection of elements, with each element having a reference to the
next element in the list.
HashMap
The HashMap class is an implementation of Map interface, which is a collection of
key-value pairs.
Set
A Set is a collection of unique elements.
PriorityQueue
A PriorityQueue is a collection of elements, with the element with the highest
priority being removed first.
Component Description
Components All elements like button, text fields, scroll bars etc.
Window A top-level container with no borders and menu bar. Windows extend
the Window class.
A top-level window with a title and border, used for taking user
Dialog
input. Dialogs extend the Dialog class.
TextArea A multi-line text input field. TextAreas extend the TextArea class.
A list of items that the user can select. Lists extend the List
List
class.
A bar that can be moved up and down or left and right to navigate
Scrollbar
through content. Scrollbars extend the Scrollbar class.
MenuBar,
Components for creating a menu system. These extend the MenuBar,
Menu, and
Menu, and MenuItem classes respectively.
MenuItem
Multithreading
Multithreading is a feature of modern programming languages that allows a single
program to perform multiple tasks concurrently. A "thread" is a single sequence of
execution in a program.
Every java program has one Main Thread provided by the JVM.
We can use multithreading by either extending the Thread class or implementing the
Runnable interface.
If multiple threads are accessing and modifying the same data, you need to ensure that
they do so in a way that doesn't cause inconsistencies or other issues. This is known
as "thread-safety".
We can use the isAlive() method to check whether a thread has finished running.