3 - Java Notes Full
3 - Java Notes Full
What is Java?
• Java is a high-level programming language that was first released in 1995 by Sun
Microsystems (now owned by Oracle Corporation).
• It is designed to be portable and platform-independent, meaning that Java code can
run on any computer or device that has a Java Virtual Machine (JVM) installed,
regardless of the underlying hardware or operating system.
• Java is commonly used for developing a wide range of applications, including web and
mobile applications, desktop software, games, and enterprise systems.
• Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in
the year 1995. James Gosling is known as the father of Java.
• Simple and Familiar: Java is designed to be easy to learn and use for developers, with
a syntax similar to C++. It also provides a standard library of pre-built functions to help
programmers perform common tasks more easily.
• Compiled and Interpreted: Java code is first compiled into an intermediate language
called bytecode, which can then be executed by a Java Virtual Machine (JVM) on any
platform that supports Java.
• Platform Independent: Java programs can run on any platform that has a Java Virtual
Machine (JVM) installed, regardless of the underlying hardware and operating system.
• Portable: Java code can be easily moved from one platform to another, as long as a
compatible JVM is available on the target platform.
• Architectural Neutral: Java is designed to be architecture-neutral, meaning that it can
run on any hardware architecture that has a compatible JVM.
• Object-Oriented: Java is based on the object-oriented programming paradigm, which
emphasizes the use of classes and objects to encapsulate data and behavior.
• Robust: Java is designed to be robust and able to handle errors and exceptions
gracefully, with features such as automatic memory management and strong type
checking.
• Secure: Java includes built-in security features, such as a bytecode verifier and a
security manager, to help prevent malicious code from executing on a system.
• Distributed: Java includes features for building distributed systems, such as remote
method invocation (RMI) and the Java Messaging Service (JMS).
• Multi-threaded and Interactive: Java supports multithreading, allowing multiple
threads to execute concurrently within a single program. It also provides a graphical
user interface (GUI) toolkit for building interactive applications.
• High Performance: Java is designed to be highly performant, with features such as
just-in-time (JIT) compilation and bytecode optimization.
• Dynamic and Extensible: Java includes features for dynamic class loading and
reflection, allowing programs to modify their behavior at runtime, and for building
extensible frameworks and libraries.
History of Java
• Java was developed in 1991 by a team of Sun engineers called the Green Team.
• Originally designed for small, embedded systems, Java was initially called "Greentalk"
and had the file extension .gt.
• In 1995, Java was renamed from "Oak" and developed as a programming language for
general-purpose use.
Java Versions
What is a Comment?
Comments in Java are the statements that are not executed by the compiler and interpreter.
Single-line Comments
• Single-line comments start with two forward slashes (//).
• Any text between // and the end of the line is ignored by Java (will not be executed).
Multi-line Comments
• Multi-line comments start with /* and ends with */.
• Any text between /* and */ will be ignored by Java.
What is a Variable?
• Variable is a name of memory location. It is used to store values.
• It is a combination of "vary + able" which means its value can be changed.
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
float 0.0f 4 byte
double 0.0d 8 byte
Rules of Identifiers
• Java keywords are also known as reserved words. Keywords are particular words
that act as a key to a code. These are predefined words by Java so they cannot be
used as a variable or object name or class name.
What is a Token in Java
• Java Tokens are the smallest individual building block or smallest unit of a
Java program
class Simple{
public static void main(String[] args){
float f=10.5f;
//int a=f; //Compile time error
int a=(int)f;
[Link](f);
[Link](a);
}}
Output:
10.5
10
What is an Operator
• Operator in Java is a symbol that is used to perform operations. For example:
+, -, *, / etc.
// Addition operator
int sum = x + y;
[Link]("Sum = " + sum);
// Subtraction operator
int difference = x - y;
[Link]("Difference = " + difference);
// Multiplication operator
int product = x * y;
[Link]("Product = " + product);
// Division operator
int quotient = x / y;
[Link]("Quotient = " + quotient);
// Modulus operator
int remainder = x % y;
[Link]("Remainder = " + remainder);
}
}
Output
Sum = 15
Difference = 5
Product = 50
Quotient = 2
Remainder = 0
int a = 4,b;
b = a;
[Link]("var using =: " + b
b += a;
[Link]("var using +=: " + var);
b *= a;
[Link]("var using *=: " + var); }
}
Output
var using =: 4
var using +=: 8
var using *=: 32
int a = 7, b = 11;
// && operator
[Link]((5 > 3) && (8 > 5)); // true
[Link]((5 > 3) && (8 < 5)); // false
// || operator
[Link]((5 < 3) || (8 > 5)); // true
[Link]((5 > 3) || (8 < 5)); // true
[Link]((5 < 3) || (8 < 5)); // false
// ! operator
[Link](!(5 == 3)); // true
[Link](!(5 > 3)); // false
}
}
// decrement operator
result2 = --b;
[Link]("After decrement: " + result2);
}
}
Output
Value of a: 12
After increment: 13
Value of b: 12
After decrement: 11
Here, str is an instance of the String class. Hence, the instanceof operator returns true. To
learn more, visit Java instanceof.
int a=1;
String result;
// ternary operator
result = (a==1) ? 1 : 0;
[Link](result);
}
}
Output
1
Control Statements
• if statement
• if-else statement
• if-else-if ladder
• nested if statement
• Switch Case
Java IF Statement
The Java if statement tests the condition. It executes the if block if condition is true.
import [Link];
[Link]("Enter a value");
int a=[Link]();
if(a<10)
[Link]("a is less than 10");
}
}
Output:
Enter a value
5
a is less than 10
The Java if-else statement also tests the condition. It executes the if block if condition is
true otherwise else block is executed.
import [Link];
public class Main
{
public static void main(String[] args) {
Scanner s = new Scanner([Link]);
[Link]("Enter a value");
int a=[Link]();
if(a<10)
[Link]("a is less than 10");
else
[Link](" a is not less than 10");
}
}
Output:
Enter a value
15
a is not less than 10
The if-else-if ladder statement executes one condition from multiple statements.
import [Link];
public class Main
{
public static void main(String[] args) {
Scanner s = new Scanner([Link]);
[Link]("Enter a value");
int a=[Link]();
if(a<10)
[Link]("a is less than 10");
else if(a>10)
[Link](" a is greater than 10");
else
[Link]("a is equal to 10");
}
}
import [Link];
public class Main
{
public static void main(String[] args) {
Scanner s = new Scanner([Link]);
[Link]("Enter a value");
int a=[Link]();
if(a==1)
[Link]("one");
else if(a==2)
[Link](" two");
else if(a==3)
[Link]("three");
else
[Link]("wrong choice");
}
}
Output:
Enter a value
3
three
The Java switch statement executes one statement from multiple conditions. It is like if-
else-if ladder statement.
import [Link];
public class Main
{
public static void main(String[] args) {
Scanner s = new Scanner([Link]);
[Link]("Enter a value");
int a=[Link]();
switch(a)
{
case 1:
[Link]("one");
break;
case 2:
[Link]("two");
break;
case 3:
[Link]("three");
break;
default:
[Link]("wrong choice");
break;
}
}
}
Output:
Enter a value
6
wrong choice
The java switch statement is fall-through. It means it executes all statement after first
match if break statement is not used with switch cases.
Java For Loop
The Java for loop is used to iterate a part of the program several times. If the number of
iteration is fixed, it is recommended to use for loop.
The simple for loop is same as C/C++. We can initialize variable, check condition and
increment/decrement value.
Example:
public class Main {
public static void main(String[] args) {
for(int i=1;i<=5;i++){
[Link](i);
}
}
}
Output:
1
2
3
4
5
The for-each loop is used to traverse array or collection in java. It is easier to use than
simple for loop because we don't need to increment value and use subscript notation.
It works on elements basis not index. It returns element one by one in the defined
variable.
Syntax:
for(Type var:array){
//code to be executed
}
Example:
public class ForEachExample {
public static void main(String[] args) {
int arr[]={12,23,44,56,78};
for(int i:arr){
[Link](i);
}
}
}
Output:
12
23
44
56
78
We can have name of each for loop. To do so, we use label before the for loop. It is useful
if we have nested for loop so that we can break/continue specific for loop.
Normally, break and continue keywords breaks/continues the inner most for loop only.
Syntax:
labelname:
for(initialization;condition;incr/decr){
//code to be executed
}
Example:
public class LabeledForExample {
public static void main(String[] args) {
aa:
for(int i=1;i<=3;i++){
bb:
for(int j=1;j<=3;j++){
if(i==2&&j==2){
break aa;
}
[Link](i+" "+j);
}
}
}
}
Output:
11
12
13
21
If you use break bb;, it will break inner loop only which is the default behavior of any
loop.
The Java while loop is used to iterate a part of the program several times. If the number of
iteration is not fixed, it is recommended to use while loop.
Syntax:
while(condition){
//code to be executed
}
Example:
public class WhileExample {
public static void main(String[] args) {
int i=1;
while(i<=10){
[Link](i);
i++;
}
}
}
Output:
1
2
3
4
5
6
7
8
9
10
The Java do-while loop is used to iterate a part of the program several times. If the number of
iteration is not fixed and you must have to execute the loop at least once, it is recommended
to use do-while loop.
The Java do-while loop is executed at least once because condition is checked after loop
body.
Syntax:
do{
//code to be executed
}while(condition);
Example:
public class DoWhileExample {
public static void main(String[] args) {
int i=1;
do{
[Link](i);
i++;
}while(i<=5);
}
}
Output:
1
2
3
4
5
The Java break is used to break loop or switch statement. It breaks the current flow of the
program at specified condition. In case of inner loop, it breaks only inner loop.
The Java continue statement is used to continue loop. It continues the current flow of the
program and skips the remaining code at specified condition. In case of inner loop, it
continues only inner loop.
Example:
public class ContinueExample {
public static void main(String[] args) {
for(int i=1;i<=10;i++){
if(i==5){
continue;
[Link](i);
}
}
}
Output:
1
2
3
4
6
7
8
9
10
JAVA ARRAY
• Array is a collection of similar type of elements that have contiguous memory
location.
• Arrays are used to store multiple values in a single variable, instead of declaring
separate variables for each value.
Advantage of Java Array
o Code Optimization: It makes the code optimized, we can retrieve or sort the data
easily.
o Random access: We can get any data located at any index position.
An array declaration has two components: the type and the name.
dataType[] arr;
(or)
dataType []arr;
(or)
dataType arr[];
In such case, data is stored in row and column based index (also known as matrix form).
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
[Link](arr[i][j]+" ");
}
[Link]();
}
}}
Output:
123
245
445
[Link]([Link]());
[Link]([Link]());
String s1upper=[Link]();
[Link](s1upper);
Output:
string length is: 5
string length is: 7
hello how are you
false
false
HELLO HOW ARE YOU
hello how are you?
The Java String length() method tells the length of the string. It returns count of total number
of characters present in the String.
The Java String concat() method combines a specific string at the end of another string and
ultimately returns a combined string. It is like appending another string.
This method checks whether the String contains anything or not. If the java String is Empty, it
returns true else false.
The java string trim() method removes the leading and trailing spaces. It checks the unicode
value of space character (‘u0020’) before and after the string. If it exists, then removes the
spaces and return the omitted string.
The java string toLowerCase() method converts all the characters of the String to lower case.
The Java String toUpperCase() method converts all the characters of the String to upper case.
Java String ValueOf():
This method converts different types of values into [Link] this method, you can convert
int to string, long to string, Boolean to string, character to string, float to string, double to
string, object to string and char array to string. The signature or syntax of string valueOf()
method is given below:
public static String valueOf(boolean b)
public static String valueOf(char c)
public static String valueOf(char[] c)
public static String valueOf(int i)
public static String valueOf(long l)
public static String valueOf(float f)
public static String valueOf(double d)
public static String valueOf(Object o)
The Java String equals() method compares the two given strings on the basis of content of the
string i.e Java String representation. If all the characters are matched, it returns true else it
will return false.
This method compares two string on the basis of content but it does not check the case like
equals() method. In this method, if the characters match, it returns true else false.
Java OOPs
What is OOPs?
Example: chair, bike, marker, pen, table, car etc. The example of intangible object is banking
system.
A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created. It is a logical entity. It can't be physical.
A class in Java can contains fields, methods, constructors, blocks, nested class and interface
class class_name{
field;
method;
}
A variable which is created inside the class but outside the method, is known as instance
variable.
Instance variable doesn't get memory at compile time. It gets memory at run time when
object(instance) is created. That is why, it is known as instance variable.
The new keyword is used to allocate memory at run time. All objects get memory in Heap
memory area.
class Student{
int id;
String name;
}
class Main{
public static void main(String args[])
{
Student s1=new Student();
Student s2=new Student();
[Link]=101;
[Link]="Raj";
[Link]=102;
[Link]="Ravi";
[Link]([Link]+" "+[Link]);
[Link]([Link]+" "+[Link]);
}
}
Output:
101 Raj
102 Ravi
class Main{
public static void main(String args[])
{
Employee e1 = new Employee();
Employee e2 = new Employee();
[Link] = 1;
[Link]="Ram";
[Link] = 10000;
[Link] = 2;
[Link]="Ramu";
[Link] = 20000;
class Employee{
int id;
String name;
double salary;
class Main{
public static void main(String args[])
{
Employee e1 = new Employee();
Employee e2 = new Employee();
[Link] = 1;
[Link]="Ram";
[Link] = 10000;
[Link] = 2;
[Link]="Ramu";
[Link] = 20000;
[Link]();
[Link]();
}
}
Output:
Employee ID: 1
Employee Name: Ram
Employee Salary: 10000.0
Employee ID: 2
Employee Name: Ramu
Employee Salary: 20000.0
class Employee{
int id;
String name;
double salary;
class Main{
public static void main(String args[])
{
Employee e1 = new Employee();
Employee e2 = new Employee();
[Link](1,"Ram",10000);
[Link](2,"Ramu",2000);
[Link]();
[Link]();
}
}
Output:
Employee ID: 1
Employee Name: Ram
Employee Salary: 10000.0
Employee ID: 2
Employee Name: Ramu
Employee Salary: 2000.0
class Employee{
int id;
String name;
double salary;
class Main{
public static void main(String args[])
{
Employee e1 = new Employee();
Employee e2 = new Employee();
[Link](1,"Ram",10000);
[Link](2,"Ramu",2000);
[Link]();
[Link]();
}
}
Output:
Employee ID: 1
Employee Name: Ram
Employee Salary: 10000.0
Employee ID: 2
Employee Name: Ramu
Employee Salary: 2000.0
class Employee{
int id;
String name;
double salary;
class Main{
public static void main(String args[])
{
Employee e1 = new Employee(1,"Ram",10000);
Employee e2 = new Employee(2,"Ramu",2000);
[Link]();
[Link]();
}
}
Output:
Employee ID: 1
Employee Name: Ram
Employee Salary: 10000.0
Employee ID: 2
Employee Name: Ramu
Employee Salary: 2000.0
class Bike1{
Bike1()
{
[Link]("Bike1 constructor invoked");
}
}
class Main{
Output:
Bike1 constructor invoked
Inheritance in Java
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object.
On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.
Note: Multiple inheritance and Hybrid is not supported in Java through class.
class Animal
{
void eat(){[Link]("eating...");}
}
class Main
{
public static void main(String args[])
{
Dog d=new Dog();
[Link]();
[Link]();
}
}
Output:
barking...
eating...
class Animal
{
void eat(){[Link]("eating...");}
}
class Dog extends Animal
{
void bark(){[Link]("barking...");}
}
class BabyDog extends Dog
{
void weep(){[Link]("weeping...");}
}
class Main
{
public static void main(String args[]){
BabyDog d=new BabyDog();
[Link]();
[Link]();
[Link]();
}
}
Output:
weeping...
barking...
eating...
class Animal
{
void eat()
{
[Link]("eating...");
}
}
class Dog extends Animal
{
void bark()
{[Link]("barking...");
}
}
class Cat extends Animal
{
void meow()
{
[Link]("meowing...");
}
}
class TestInheritance3
{
public static void main(String args[])
{
Cat c=new Cat();
[Link]();
[Link]();
//[Link]();//[Link]
}
}
Output:
meowing...
eating...
Polymorphism in Java
Polymorphism in java is a concept by which we can perform a single action by different ways.
Polymorphism is derived from 2 greek words: poly and morphs. The word "poly" means many
and "morphs" means forms. So polymorphism means many forms.
If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in java.
Example :
class Vehicle
{
void run()
{
[Link]("Vehicle is running");
}
}
Output:
Bike is running safely
Method Overloading
If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.
class Adder{
class TestOverloading1
{
public static void main(String[] args)
{
[Link]([Link](11,11));
[Link]([Link](11,11,11));
}
}
Output:
22
33
ABSTRACTION
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality
to the user.
• A class that is declared with abstract keyword, is known as abstract class in java. It can
have abstract (method without body) and non-abstract methods (method with body).
• It needs to be extended and its method implemented. It cannot be instantiated.
Abstract method
• A method that is declared as abstract and does not have implementation is known as
abstract method.
Rule: If there is any abstract method in a class, that class must be abstract.
Interface in Java
• An interface in java is a blueprint of a class. It has static constants and abstract
methods.
• The interface in java is a mechanism to achieve abstraction. There can be only abstract
methods in the java interface not method body. It is used to achieve abstraction and
multiple inheritance in Java.
• Java Interface also represents IS-A relationship.
• It cannot be instantiated just like abstract class.
There are mainly three reasons to use interface. They are given below.
The java compiler adds public and abstract keywords before the interface method. More, it
adds public, static and final keywords before data members.
In other words, Interface fields are public, static and final by default, and methods are public
and abstract.
As shown in the figure given below, a class extends another class, an interface extends
another interface but a class implements an interface.
interface printable
{
void print();
}
class A6 implements printable
{
public void print(){[Link]("Hello");
}
Encapsulation in Java
Encapsulation in java is a process of wrapping code and data together into a single unit, for
example capsule i.e. mixed of several medicines.
We can create a fully encapsulated class in java by making all the data members of the class
private. Now we can use setter and getter methods to set and get the data in it.
• private
• default
• protected
• public
There are many non-access modifiers such as static, abstract, synchronized, native, volatile,
transient etc.
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
In this example, we have created two classes A and Simple. A class contains private data
member and private method. We are accessing these private members from outside the
class, so there is compile time error.
Example
class A
{
private int data=40;
private void msg(){[Link]("Hello java");}
}
If you don't use any modifier, it is treated as default bydefault. The default modifier is
accessible only within package.
We have created two packages pack and mypack. We are accessing the A class from outside
its package, since A class is not public, so it cannot be accessed from outside the package.
[Link] [Link]
package pack; package mypack;
class A import pack.*;
{ class B{
void msg() public static void main(String args[]){
{ A obj = new A(); //Compile Time Error
[Link]("Hello"); [Link](); //Compile Time Error
} }
} }
In the above program, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.
The protected access modifier is accessible within package and outside the package but
through inheritance only. The protected access modifier can be applied on the data
member, method and constructor. It can't be applied on the class.
[Link] [Link]
The public access modifier is accessible everywhere. It has the widest scope among all
other modifiers.
[Link] [Link]
package pack; package mypack;
public class A{ import pack.*;
public void msg()
{ class B{
[Link]("Hello"); public static void main(String args[]){
} A obj = new A();
} [Link]();
}
}
Output:
Hello
This Keyword
The this keyword can be used to refer current class instance variable. If there is ambiguity
between the instance variables and parameters, this keyword resolves the problem of
ambiguity.
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
[Link]=rollno;
[Link]=name;
[Link]=fee;
}
void display(){[Link](rollno+" "+name+" "+fee);}
}
class Main{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000);
Student s2=new Student(112,"sumit",6000);
[Link]();
[Link]();
}}
Output:
111 ankit 5000
112 sumit 6000
If local variables(formal arguments) and instance variables are different, there is no need to
use this keyword
static keyword
The static keyword in java is used for memory management mainly. We can apply java static
keyword with variables, methods, blocks and nested class. The static keyword belongs to the
class than instance of the class.
o The static variable can be used to refer the common property of all objects
o The static variable gets memory only once in class area at the time of class loading.
class Student8{
int rollno;
String name;
static String college ="Gayathri College";
[Link]();
[Link]();
}
}
Output:
111 Ram Gayathri College
222 Arjun Gayathri College
• If you apply static keyword with any method, it is known as static method.A static
method belongs to the class rather than object of a class. A static method can be
invoked without the need for creating an instance of a class. Static method can access
static data member and can change the value of it.
class Student9{
int rollno;
String name;
static String college = "ITS";
[Link]();
[Link]();
[Link]();
[Link]();
}
}
Output:
111 Karan ITS
222 Aryan ITS
333 Sonoo BBDIT
The super keyword in java is a reference variable which is used to refer immediate parent
class object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly
which is referred by super reference variable.
We can use super keyword to access the data member or field of parent class. It is used if
parent class and child class have same fields.
class Animal
{
String color="white";
}
class Dog extends Animal
{
String color="black";
void printColor(){
[Link](color);//prints color of Dog class
[Link]([Link]);//prints color of Animal class
}
}
class TestSuper1
{
public static void main(String args[])
{
Dog d=new Dog();
[Link]();
}
}
Output:
black
white
In the above example, Animal and Dog both classes have a common property color. If we
print color property, it will print the color of current class by default. To access the parent
property, we need to use super keyword.
The super keyword can also be used to invoke parent class method. It should be used if
subclass contains the same method as parent class. In other words, it is used if method is
overridden.
class Animal
{
void eat(){[Link]("eating...");
}
}
class Dog extends Animal
{
void eat(){[Link]("eating bread...");
}
void bark(){[Link]("barking...");}
void work()
{
[Link]();
bark();
}
}
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
[Link]();
}}
Output:
eating...
barking...
In the above example Animal and Dog both classes have eat() method if we call eat() method
from Dog class, it will call the eat() method of Dog class by default because priority is given to
local.
}
}
Output:
Exception in thread "main" [Link]: / by zero
import [Link];
public class Main
{
public static void main(String[] args) {
Scanner s = new Scanner([Link]);
[Link]("Enter two values ");
int a= [Link]();
int b = [Link]();
int c;
try {
c=a/b; //may throw exception
}
catch(ArithmeticException e)
{
[Link](e);
}
[Link]("rest of the code");
[Link]("rest of the code");
}
}
Output:
[Link]: / by zero
rest of the code
There are mainly two types of exceptions: checked and unchecked. Here, an error is
considered as the unchecked exception. According to Oracle, there are three types of
exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
Java Exception Handling where we using a try-catch statement to handle the exception.
Output:
Exception in thread main [Link]:/ by zero
rest of the code...
There are given some scenarios where unchecked exceptions may occur. They are as follows:
[Link] exception
2) NullPointerException
If we have a null value in any variable, performing any operation on the variable throws a
NullPointerException.
String s=null;
[Link]([Link]()); //NullPointerException
3) NumberFormatException
The wrong formatting of any value may occur NumberFormatException. Suppose I have a
string variable that has characters, converting this variable into digit will occur
NumberFormatException.
String s="abc";
int i=[Link](s);//NumberFormatException
4) ArrayIndexOutOfBoundsException
If you are inserting any value in the wrong index, it would result in
ArrayIndexOutOfBoundsException as shown below:
Java try block is used to enclose the code that might throw an exception. It must be used
within the method.
If an exception occurs at the particular statement of try block, the rest of the block code will
not execute. So, it is recommended not to keeping the code in try block that will not throw an
exception.
Java try block must be followed by either catch or finally block.
Java catch block is used to handle the Exception by declaring the type of exception within the
parameter. The declared exception must be the parent class exception ( i.e., Exception) or the
generated exception type. However, the good approach is to declare the generated type of
exception.
The catch block must be used after the try block only. You can use multiple catch block with a
single try block.
Example
Output:
[Link]: / by zero
rest of the code
Example to print a custom message on exception.
public class TryCatchExample5 {
Output:
Can't divided by zero
Example to resolve the exception in a catch block.
Output:
25
}
// try to handle the ArithmeticException using ArrayIndexOutOfBoundsException
catch(ArrayIndexOutOfBoundsException e)
{
[Link](e);
}
[Link]("rest of the code");
}
Output:
Exception in thread "main" [Link]: / by zero
Output:
[Link]: 10
rest of the code
Example to handle checked exception.
import [Link];
import [Link];
PrintWriter pw;
try {
pw = new PrintWriter("[Link]"); //may throw exception
[Link]("saved");
}
// providing the checked exception handler
catch (FileNotFoundException e) {
[Link](e);
}
[Link]("File saved successfully");
}
}
Output:
File saved successfully
A try block can be followed by one or more catch blocks. Each catch block must contain a
different exception handler. So, if you have to perform different tasks at the occurrence of
different exceptions, use java multi-catch block.
Points to remember
At a time only one exception occurs and at a time only one catch block is executed.
All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.
try{
int a[]=new int[5];
a[7]=30/0;
}
catch(ArithmeticException e)
{
[Link]("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
[Link]("Parent Exception occurs");
}
[Link]("rest of the code");
}
}
Output:
Arithmetic Exception occurs
rest of the code
Example 2
try{
int a[]=new int[5];
[Link](a[10]);
}
catch(ArithmeticException e)
{
[Link]("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
[Link]("Parent Exception occurs");
}
[Link]("rest of the code");
}
}
Output:
ArrayIndexOutOfBounds Exception occurs
rest of the code
Example 3
In this example, try block contains two exceptions. But at a time only one exception occurs
and its corresponding catch block is invoked.
try{
int a[]=new int[5];
a[5]=30/0;
[Link](a[10]);
}
catch(ArithmeticException e)
{
[Link]("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
[Link]("Parent Exception occurs");
}
[Link]("rest of the code");
}
}
Output:
Arithmetic Exception occurs
rest of the code
Example 4
In this example, we generate NullPointerException, but didn't provide the corresponding
exception type. In such case, the catch block containing the parent exception
class Exception will invoked.
try{
String s=null;
[Link]([Link]());
}
catch(ArithmeticException e)
{
[Link]("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
[Link]("Parent Exception occurs");
}
[Link]("rest of the code");
}
}
Output:
Parent Exception occurs
rest of the code
Example 5
Let's see an example, to handle the exception without maintaining the order of exceptions
(i.e. from most specific to most general).
class MultipleCatchBlock5{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(Exception e){[Link]("common task completed");}
catch(ArithmeticException e){[Link]("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e){[Link]("task 2 completed");}
[Link]("rest of the code...");
}
}
Output:
Compile-time error
The try block within a try block is known as nested try block in java.
Sometimes a situation may arise where a part of a block may cause one error and the entire
block itself may cause another error. In such cases, exception handlers have to be nested.
Syntax:
....
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}
....
try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){[Link](e);}
[Link]("other statement);
}catch(Exception e){[Link]("handeled");}
[Link]("normal flow..");
}
}
• Java finally block is a block that is used to execute important code such as closing
connection, stream etc.
• Java finally block is always executed whether exception is handled or not.
• Java finally block follows try or catch block.
Note: If you don't handle exception, before terminating the program, JVM executes finally
block(if any).
Finally block in java can be used to put "cleanup" code such as closing a file, closing
connection etc.
Let's see the different cases where java finally block can be used.
Case 1
Let's see the java finally example where exception doesn't occur.
class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
[Link](data);
}
catch(NullPointerException e){[Link](e);}
finally{[Link]("finally block is always executed");}
[Link]("rest of the code...");
}
}
Output:
5
finally block is always executed
rest of the code...
Case 2
class TestFinallyBlock1{
public static void main(String args[]){
try{
int data=25/0;
[Link](data);
}
catch(NullPointerException e){[Link](e);}
finally{[Link]("finally block is always executed");}
[Link]("rest of the code...");
}
}
Output:
finally block is always executed
Exception in thread main [Link]:/ by zero
Case 3
syntax
throw exception;
example
Output:
Exception in thread main [Link]:not valid
The Java throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception so it is better for the programmer to provide
the exception handling code so that normal flow can be maintained.
Output:
exception handled
normal flow...
Rule: If you are calling a method that declares an exception, you must either caught or
declare the exception.
Case1:You caught the exception i.e. handle the exception using try/catch.
Case2:You declare the exception i.e. specifying throws with the method.
Case1:
import [Link].*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
}
public class Testthrows2{
public static void main(String args[]){
try{
M m=new M();
[Link]();
}catch(Exception e){[Link]("exception handled");}
[Link]("normal flow...");
}
}
Output:
exception handled
normal flow...
Case2:
B)In case you declare the exception if exception occures, an exception will be thrown at
runtime because throws does not handle the exception.
[Link]("normal flow...");
}
}
Output:device operation performed
normal flow...
[Link]("normal flow...");
}
}
Output:Runtime Exception
void m(){
throw new ArithmeticException("sorry");
}
If you are creating your own Exception that is known as custom exception or user-defined
exception. Java custom exceptions are used to customize the exception according to user
need. By the help of custom exception, you can have your own exception and message.
Example
class InvalidAgeException extends Exception{
InvalidAgeException(String s){
super(s);
}
}
class TestCustomException1{
Multithreading in Java
• Multithreading in java is a process of executing multiple threads simultaneously.
• Thread is basically a lightweight sub-process, a smallest unit of processing.
Multiprocessing and multithreading, both are used to achieve multitasking.
• But we use multithreading than multiprocessing because threads share a common
memory area. They don't allocate separate memory area so saves memory, and
context-switching between the threads takes less time than process.
• Java Multithreading is mostly used in games, animation etc.
1) It doesn't block the user because threads are independent and you can perform multiple
operations at same time.
3) Threads are independent so it doesn't affect other threads if exception occur in a single
thread.
Multitasking
o Process-based Multitasking(Multiprocessing)
o Thread-based Multitasking(Multithreading)
Threads are independent, if there occurs exception in one thread, it doesn't affect other
threads. It shares a common memory area.
As shown in the above figure, thread is executed inside the process. There is context-
switching between the threads. There can be multiple processes inside the OS and one
process can have multiple threads.
Thread class:
Thread class provide constructors and methods to create and perform operations on a
[Link] class extends Object class and implements Runnable interface.
The Thread class provides methods to change and get the name of a thread. By default, each
thread has a name i.e. thread-0, thread-1 and so on. By we can change the name of the
thread by using setName() method. The syntax of setName() and getName() methods are
given below:
[Link]();
[Link]();
[Link]("Sonoo Jaiswal");
[Link]("After changing name of t1:"+[Link]());
}
}
Output:
Name of t1:Thread-0
Name of t2:Thread-1
running…
running...
After changeling name of t1:Sonoo Jaiswal
Running
The join() method waits for a thread to die. In other words, it causes the currently running
threads to stop executing until the thread it joins with completes its task.
Syntax:
[Link]();
[Link]();
}
}
Output:1
2
3
4
5
1
1
2
2
3
3
4
4
5
5
As you can see in the above example,when t1 completes its task then t2 and t3 starts
executing.
[Link]();
[Link]();
[Link]("Sonoo Jaiswal");
[Link]("After changing name of t1:"+[Link]());
}
}
Output:
Name of t1:Thread-0
Name of t2:Thread-1
id of t1:8
running...
After changling name of t1:Sonoo Jaiswal
running...
Each thread have a priority. Priorities are represented by a number between 1 and 10. In
most cases, thread schedular schedules the threads according to their priority (known as
preemptive scheduling). But it is not guaranteed because it depends on JVM specification
that which scheduling it chooses.
Here, the video conferencing application requires real-time processing, which means that
the video frames have to be captured and displayed immediately without any delay. On
the other hand, the heavy workload application can take some time to complete its
execution. So, in this case, the thread running the video conferencing application can be
given a higher priority than the thread running the heavy workload application.
By giving a higher priority to the thread running the video conferencing application, the
operating system will allocate more CPU time to that thread, ensuring that the video
frames are captured and displayed without any delay. This way, thread priority can be
used to ensure that important tasks are executed with higher priority, while other tasks
are executed with lower priority.
}
public static void main(String args[]){
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
[Link](Thread.MIN_PRIORITY);
[Link](Thread.MAX_PRIORITY);
[Link]();
[Link]();
}
}
Output:running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1
The sleep() method of Thread class is used to sleep a thread for the specified amount of time.
[Link]();
[Link]();
}
}
Output:
1
1
2
2
3
3
4
4
As you know well that at a time only one thread is executed. If you sleep a thread for the
specified time,the thread shedular picks up another thread and so on.
COLLECTIONS IN JAVA
A Collection is a group of individual objects represented as a single unit. Java provides
Collection Framework which defines several classes and interfaces to represent a group of
objects as a single unit.
The Collection interface ([Link]) and Map interface ([Link]) are the two
main “root” interfaces of Java collection classes.
Java Collections
1. ArrayList
2. LinkedList
3. Vector
4. HashSet
5. LinkedHashSet
6. TreeSet
7. HashMap
8. TreeMap
9. LinkedHashMap
10. Hashtable
11. Iterator and ListIterator
ArrayList A dynamic array implementation in Java, allowing for resizable arrays with
constant time access to elements
HashSet A collection that does not allow duplicates and provides constant time
performance for add, remove, and contains operations
LinkedHashSet
A collection that maintains the order of elements as they were inserted, while
Data Structure Definition
TreeSet A sorted set implementation in Java, where elements are ordered using their
natural ordering, or by a Comparator object
HashMap A key-value pair data structure that allows for fast retrieval of values based on
their associated keys
TreeMap A sorted map implementation in Java, where keys are sorted using their natural
ordering, or by a Comparator object
LinkedHashMap A map that maintains the order of entries as they were inserted, while still
allowing for fast retrieval of values based on their associated keys
Iterator and Interfaces used for iterating over collections, where Iterator is used for iterating
ListIterator forward, and ListIterator is used for iterating in both directions
A List is an ordered Collection (sometimes called a sequence). Lists may contain duplicate
elements. Elements can be inserted or accessed by their position in the list, using a zero-
based index.
ArrayList
• ArrayList is a dynamic data structure in Java that can be used to store and manipulate a
collection of elements.
• It is similar to an array but provides additional features such as automatic resizing and the
ability to insert or remove elements at any position.
• ArrayList is part of the Java Collections Framework and can be used to store objects of any
class or primitive data types.
Syntax:
ArrayList<String> alist=new ArrayList<String>();
Program
import [Link];
import [Link];
public class ArrayListExample {
public static void main(String[] args) {
// Create an ArrayList of integers
ArrayList<Integer> numbers = new ArrayList<>();
// Add elements to the ArrayList
[Link](5);
[Link](2);
[Link](8);
[Link](1);
// Print the original ArrayList
[Link]("Original ArrayList: " + numbers);
// Remove an element from the ArrayList
[Link](2);
// Print the ArrayList after removing an element
[Link]("ArrayList after removing an element: " + numbers);
// Sort the ArrayList
[Link](numbers);
// Print the sorted ArrayList
[Link]("Sorted ArrayList: " + numbers);
}
}
LinkedList in Java
LinkedList Program
import [Link];
public class LinkedListExample {
public static void main(String[] args) {
// Creating a Linked List
LinkedList<String> linkedList = new LinkedList<>();
// Adding elements to the Linked List
[Link]("Java");
[Link]("Python");
[Link]("JavaScript");
[Link]("LinkedList: " + linkedList);
// Adding an element at the first position
[Link]("C++");
[Link]("After adding an element at first position: " + linkedList);
// Adding an element at the last position
[Link]("Ruby");
[Link]("After adding an element at last position: " + linkedList);
// Removing the first element
[Link]();
[Link]("After removing the first element: " + linkedList);
// Removing the last element
[Link]();
[Link]("After removing the last element: " + linkedList);
// Sorting the Linked List in ascending order
[Link](String::compareTo);
[Link]("After sorting the Linked List: " + linkedList);
}
}
Vector in Java
• Vector is a dynamic array-like data structure that can resize itself automatically when
elements are added or removed from it.
• It is a part of the Java Collections Framework and is similar to ArrayList in many ways, but
with some additional features.
• Vector is thread-safe, which means that it can be accessed by multiple threads
simultaneously without causing any concurrency issues. However, this can come at the
cost of performance, so it is generally recommended to use ArrayList if you don't need
thread safety.
Vector Program
import [Link];
public class VectorExample {
public static void main(String[] args) {
// create a vector of strings
Vector<String> v = new Vector<String>();
// add elements to the vector
[Link]("apple");
[Link]("banana");
[Link]("cherry");
// print the vector
[Link]("Vector: " + v);
// add an element at a specific index
[Link](1, "grape");
// print the vector again
[Link]("Vector after adding 'grape' at index 1: " + v);
// remove an element at a specific index
[Link](2);
// print the vector again
[Link]("Vector after removing element at index 2: " + v);
}
}
import [Link];
public class HashSetExample {
public static void main(String[] args) {
HashSet<String> fruits = new HashSet<>();
// Adding elements to the HashSet
[Link]("Apple");
[Link]("Banana");
[Link]("Orange");
[Link]("Pineapple");
// Printing the HashSet
[Link]("Fruits: " + fruits);
// Checking if an element is present in the HashSet
boolean isPresent = [Link]("Grapes");
[Link]("Is Grapes present? " + isPresent);
// Removing an element from the HashSet
[Link]("Pineapple");
// Printing the HashSet after removal
[Link]("Fruits after removal: " + fruits);
// Iterating over the HashSet using for-each loop
[Link]("Iterating over the HashSet:");
for (String fruit : fruits) {
[Link](fruit);
}
// Clearing the HashSet
[Link]();
[Link]("Fruits after clearing: " + fruits);
}
}
TreeSet Class in Java
import [Link];
public class HashSetExample {
public static void main(String[] args) {
HashSet<String> fruits = new HashSet<>();
// Adding elements to the HashSet
[Link]("Apple");
[Link]("Banana");
[Link]("Orange");
[Link]("Pineapple");
// Printing the HashSet
[Link]("Fruits: " + fruits);
// Checking if an element is present in the HashSet
boolean isPresent = [Link]("Grapes");
[Link]("Is Grapes present? " + isPresent);
// Removing an element from the HashSet
[Link]("Pineapple");
// Printing the HashSet after removal
[Link]("Fruits after removal: " + fruits);
// Iterating over the HashSet using for-each loop
[Link]("Iterating over the HashSet:");
for (String fruit : fruits) {
[Link](fruit);
}
// Clearing the HashSet
[Link]();
[Link]("Fruits after clearing: " + fruits);
}
}
HashSet TreeSet
HashMap in Java
Hashmap Program
import [Link];
public class HashMapExample {
public static void main(String[] args) {
// Creating a HashMap with Integer keys and String values
HashMap<Integer, String> map = new HashMap<>();
// Adding key-value pairs to the HashMap
[Link](1, "John");
[Link](2, "Jane");
[Link](3, "Bob");
[Link](4, "Alice");
// Retrieving values from the HashMap using keys
String name1 = [Link](1);
String name3 = [Link](3);
[Link]("Name at key 1: " + name1);
[Link]("Name at key 3: " + name3);
// Removing a key-value pair from the HashMap
[Link](4);
// Iterating over the HashMap and printing all key-value pairs
for (Integer key : [Link]()) {
String value = [Link](key);
[Link]("Key: " + key + ", Value: " + value);
}
}
}
TreeMap in Java
• TreeMap is a class in Java's collections framework that provides a sorted map data
structure. It implements the Map interface, and allows key-value pairs to be stored in a
sorted order based on the keys.
• TreeMap uses a red-black tree data structure to maintain the key-value pairs in a sorted
order. This allows for efficient insertion, deletion, and retrieval operations with a worst-
case time complexity of O(log n).
• TreeMap provides methods to retrieve the first and last keys in the sorted order, as well
as methods to retrieve keys that are less than or greater than a given key. It also supports
a variety of methods for manipulating and iterating over the key-value pairs in the map.
TreeMap Program
import [Link].*;
public class TreeMapExample {
public static void main(String[] args) {
// Create a TreeMap
TreeMap<String, Integer> treeMap = new TreeMap<>();
// Add elements to the TreeMap
[Link]("Alice", 25);
[Link]("Bob", 30);
[Link]("Charlie", 35);
[Link]("David", 40);
// Print the TreeMap
[Link]("TreeMap: " + treeMap);
// Get the size of the TreeMap
[Link]("Size of TreeMap: " + [Link]());
// Check if the TreeMap contains a key
[Link]("TreeMap contains key 'Alice': " + [Link]("Alice"));
// Get the value associated with a key
[Link]("Value associated with key 'Bob': " + [Link]("Bob"));
// Remove an element from the TreeMap
[Link]("Charlie");
[Link]("TreeMap after removing 'Charlie': " + treeMap);
// Iterate over the TreeMap
[Link]("Iterating over TreeMap using entrySet():");
for ([Link]<String, Integer> entry : [Link]()) {
[Link]([Link]() + " : " + [Link]());
}
}
}
LinkedHashMap in Java
• It maintains the order of insertion of elements, so the order in which elements are added
to the map is preserved.
• It provides a predictable iteration order, which is either the order of insertion or the order
of access (least-recently accessed to most-recently accessed).
• It has slightly slower performance than a regular HashMap due to the added overhead of
maintaining the linked list, but this is often negligible for small maps and can be worth it
for the benefits of maintaining order.
LinkedHashMap Program:
import [Link];
import [Link];
public class LinkedHashMapExample {
public static void main(String[] args) {
// Creating a LinkedHashMap of String keys and Integer values
Map<String, Integer> map = new LinkedHashMap<>();
// Adding key-value pairs to the LinkedHashMap
[Link]("John", 25);
[Link]("Sarah", 30);
[Link]("David", 40);
// Printing the contents of the LinkedHashMap
[Link]("Initial LinkedHashMap: " + map);
// Replacing the value for the key "Sarah"
[Link]("Sarah", 35);
// Removing the key-value pair for the key "David"
[Link]("David");
// Printing the updated contents of the LinkedHashMap
[Link]("Updated LinkedHashMap: " + map);
// Iterating over the keys and values of the LinkedHashMap using a for-each loop
for ([Link]<String, Integer> entry : [Link]()) {
[Link]([Link]() + " = " + [Link]());
}
}
}
Hashtable in java
• Hashtable is a data structure used for storing key-value pairs in Java.
• It uses the hash code of the key to store and retrieve values in a highly efficient way.
• Hashtable is synchronized, which means it is thread-safe and can be used in a multi-
threaded environment without any issues related to race conditions or thread
interference.
Hashtable Program
import [Link];
import [Link];
import [Link];
import [Link];
public class LinkedHashtableExample {
public static void main(String[] args) {
// Creating a new linked hashtable
LinkedHashMap<String, String> linkedHashtable = new LinkedHashMap<String, String>();
// Adding elements to the linked hashtable
[Link]("A", "Apple");
[Link]("B", "Ball");
[Link]("C", "Cat");
// Displaying the linked hashtable
[Link]("LinkedHashtable contents:");
[Link](linkedHashtable);
// Using an iterator to iterate over the linked hashtable
Iterator<[Link]<String, String>> iterator = [Link]().iterator();
while ([Link]()) {
[Link]<String, String> entry = [Link]();
[Link]("Key = " + [Link]() + ", Value = " + [Link]());
}
}
}
HashMap Hashtable
Synchronization Not synchronized Synchronized
Java Iterator
In Java, an iterator is an interface that allows you to iterate over a collection of elements.
Iterator Program
import [Link];
import [Link];
public class IteratorExample {
public static void main(String[] args) {
// Create an ArrayList of integers
ArrayList<Integer> numbers = new ArrayList<Integer>();
// Add some integers to the ArrayList
[Link](10);
[Link](20);
[Link](30);
[Link](40);
// Get an iterator for the ArrayList
Iterator<Integer> iterator = [Link]();
// Use the iterator to print out the contents of the ArrayList
while ([Link]()) {
[Link]([Link]());
}
}
}
ListIterator in Java
import [Link];
import [Link];
public class ListIteratorExample {
public static void main(String[] args) {
// Creating an ArrayList
ArrayList<String> names = new ArrayList<>();
// Adding elements to the ArrayList
[Link]("Alice");
[Link]("Bob");
[Link]("Charlie");
[Link]("David");
// Creating a ListIterator
ListIterator<String> iterator = [Link]();
// Iterating forward through the list
while ([Link]()) {
[Link]([Link]());
}
// Iterating backward through the list
while ([Link]()) {
[Link]([Link]());
}
}
}
Java Package
//save as [Link]
package mypack;
public class Simple{
public static void main(String args[]){
[Link]("Welcome to package");
}
}
There are three ways to access the package from outside the package.
1. import package.*;
2. import [Link];
3. fully qualified name.
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but
not subpackages.
The import keyword is used to make the classes and interface of another package accessible
to the current package.
class B{
public static void main(String args[]){
A obj = new A();
[Link]();
}
}
Output:Hello
2) Using [Link]
If you import [Link] then only declared class of this package will be accessible.
package pack;
public class A{
public void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
[Link]();
}
}
Output:Hello
If you use fully qualified name then only declared class of this package will be accessible. Now
there is no need to import. But you need to use fully qualified name every time when you are
accessing the class or interface.
It is generally used when two packages have same class name e.g. [Link] and [Link]
packages contain Date class.
If you import a package, all the classes and interface of that package will be imported
excluding the classes and interfaces of the subpackages. Hence, you need to import the
subpackage as well.
Subpackage in java
Package inside the package is called the subpackage. It should be created to categorize the
package further.
Example of Subpackage
package [Link];
class Simple{
public static void main(String args[]){
[Link]("Hello subpackage");
}
}
Output:Hello subpackage
Wrapper classes provide a way to use primitive data types (int, boolean, etc..) as objects.
The table below shows the primitive type and the equivalent wrapper class:
byte Byte
short Short
int Integer
long Long
float Float
double Double
boolean Boolean
Char Character
Sometimes you must use wrapper classes, for example when working with Collection objects,
such as ArrayList, where primitive types cannot be used (the list can only store objects):
Example
To create a wrapper object, use the wrapper class instead of the primitive type. To get the
value, you can just print the object:
Example
public class Main {
public static void main(String[] args) {
Integer myInt = 5;
Double myDouble = 5.99;
Character myChar = 'A';
[Link](myInt);
[Link](myDouble);
[Link](myChar);
}
}
Since you're now working with objects, you can use certain methods to get information about
the specific object.
For example, the following methods are used to get the value associated with the
corresponding wrapper
object: intValue(), byteValue(), shortValue(), longValue(), floatValue(), doubleValue(), charValue(), booleanV
alue().
This example will output the same result as the example above:
Example
In the following example, we convert an Integer to a String, and use the length() method of
the String class to output the length of the "string":
Example
public class Main {
public static void main(String[] args) {
Integer myInt = 100;
String myString = [Link]();
[Link]([Link]());
}
}