0% found this document useful (0 votes)
9 views76 pages

Unit 1

Uploaded by

ainapuresunny07
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)
9 views76 pages

Unit 1

Uploaded by

ainapuresunny07
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
You are on page 1/ 76

UNIT-1

Introduction to java

Java is a high-level, object-oriented programming language developed by Sun Microsystems in


1995. It is platform-independent, which means we can write code once and run it anywhere
using the Java Virtual Machine (JVM).

It is used for:

 Mobile applications (specially Android apps)


 Desktop applications
 Web applications
 Web servers and application servers
 Games
 Database connection
 And much, much more!

Why Use Java?

 Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.)
 It is one of the most popular programming languages in the world
 It has a large demand in the current job market
 It is easy to learn and simple to use
 It is open-source and free
 It is secure, fast and powerful
 It has huge community support (tens of millions of developers)
 Java is an object oriented language which gives a clear structure to programs and allows
code to be reused, lowering development costs
 As Java is close to C++ and C#, it makes it easy for programmers to switch to Java or vice
versa

FeaturesofJavaareas follows:

1. CompiledandInterpreted

2. PlatformIndependentandportable

3. Object-oriented

4. Robustandsecure

5. Distributed

6. Familiar,simpleandsmall
7. MultithreadedandInteractive

8. Highperformance

9. DynamicandExtensible

1. Compiled and Interpreted -Basically a computer language is either compiled or


interpreted. Java comes together both these approach thus making Java a two-stage
system.

Java compiler translates Java code to Byte code instructions and Java Interpreter
generate machine code thatcanbe directlyexecutedbymachine thatis running
theJavaprogram.

2. Platform Independent and portable - Java supports the feature portability. Java
programs can be easily moved from one computer system to another and anywhere.
Changes and upgrades in operating systems,processors and system resources will not
force any alteration in Java programs. This is reason why Java has become a trendy
language for programming on Internet which interconnects different kind of systems
worldwide. Java certifies portability in two ways.

3. Object- oriented - Java is truly object-oriented language. In Java, almost everything is


an Object. All program code and data exist in objects and classes. Java comes with an
extensive set of classes;
organizeinpackagesthatcanbeusedinprogrambyInheritance.TheobjectmodelinJavaistrou
ble- free and easy to enlarge.

4. Robust and secure - Java is a most strong language which provides many securities to
make certainreliablecode.Itisdesignasgarbage–
collectedlanguage,whichhelpstheprogrammers
Virtuallyfromallmemorymanagementproblems.Javaalsoincludestheconceptofexception
handling, which detain serious errors and reduces all kind of threat of crashing the
system.

SecurityisanimportantfeatureofJavaandthisisthestrongreasonthatprogrammerusethis language
for programming on Internet.

5. Distributed- Java iscalledasDistributedlanguagefor constructapplications on


networkswhich can contribute both data and programs. Java applications can open and
access remote objects on Interneteasily.Thatmeansmultipleprogrammersatmultiple
remotelocationstoworktogetheron single task.
6. Simple andsmall - Java is very smalland simple language.Java does not use pointerand
header files, goto statements, etc. It eliminates operator overloading and multiple
inheritance.

7. Multithreaded - and Interactive Multithreaded means managing multiple tasks


simultaneously. Java maintainsmultithreaded programs. Thatmeanswe need notwaitfor
the applicationto complete one task before starting next task. This feature is helpful for
graphic applications.

8. Highperformance-Javaperformanceisveryextraordinaryforan
interpretedlanguage,majorly due to the use of intermediate bytecode. Java architecture
is also designed to reduce overheads during runtime. The incorporation of
multithreading improves the execution speed of program.

9. DynamicandExtensible-
Javaisalsodynamiclanguage.Javaiscapableofdynamicallylinkingin new class,
libraries,methods and objects.Java can also establishthe type of classthrough the query
building it possible to either dynamically link or abort the program, depending on the
reply.

Simple Java Program

classFirstProgram
{
publicstaticvoidmain(String[] args)
{
System.out.println(“WelcometoJAVA”);
}
}

Class declaration – The first line classFirstProgram declaresa class.Where classisa keyword and
FirstProgram is a java identifier that specifies the name of the class to be defined.

Opening braces { - Every class definition in java begins with an opening brace and ends
with matching closing brace.

The main line

Publicstaticvoidmain(Stringargs[])
It defines a method named main this is similar to main function in C or C++.Every
java application program must include the main method. This is a starting point for the
interpreter to begin the execution of the program.

public –Thekeywordpublicisanaccess specifierthatdeclaresthemainmethodas unprotected.

static –Themainmethodmustalways be declaredasstaticsince the


interpreterusesthismain method before many objects are created.

void–The type modifiervoidstatesthatthemainmethoddoesnotreturn any value.

main-Themainindicatesthatthe startupofour program.

Stringargs[]–
hereStringargs[]declaresaparameternamedargswhichcontainsanarrayofobject of the
class type String.

The output line--System.out.println(“WelcometoJAVA”);

This is similar to printf function is C or cout construct of C++. Println method is the
member of the out object which is static data member of System class.
JAVAPROGRAMSTRUCTURE

Describe the structure of typical java program.

1. Documentation Statement

Documentationsectionisnothingbutthe
commentlinesgivingthenameoftheprogram,theauthor and other details.

2. Package Statement

The first statement allowed in java file is package statement. This statement declares
the packagename and informs the compiler that the classes defined here belongs to this
package.

3. Import statement

The next thing after a package statement may be a number of import statements. This is
similar to the #include statement in C.

4. Interface Statement

An interface is like a class but includes a group of methods declarations.

5. Class Definition

A java program may contain multiple class definitions. Classes are primary and essential
elements of java program.

6. Main method class

Everyjavastandaloneprogramrequiresamainmethodasitsstartingpoint,thisclassistheessen
tial part of java program.
Understanding Hello World Program in Java
When we learn any programming language, the first step is writing a simple program to display
"Hello World". So, here is a simple Java program that displays "Hello World" on the screen.
Java Hello World Program:
// This is a simple Java program to print Hello World!
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}

Output
Hello World!
How does this work:
 // starts a single-line comment. The comments does not executed by Java.
 public class HelloWorld defines a class named HelloWorld. In Java, every program must be
inside a class.
 public static void main(String[] args) is the entry point of any Java application. It tells
the JVM where to start executing the program.
 System.out.println("Hello, World!"); prints the message to the console.

Java program execution follows this below simple flow:


 Write code in a file like HelloWorld.java.
 The Java Compiler "javac" compiles it into bytecode "HelloWorld.class".[ In Java, bytecode is
an intermediate, low-level, and platform-independent code generated by the Java compiler
(javac) from Java source code (.java files). It is a set of instructions designed to be executed by
the Java Virtual Machine (JVM).]
 The JVM (Java Virtual Machine) reads the .class file and interprets the bytecode.
 JVM converts bytecode to machine readable code i.e. "binary" (001001010) and then execute
the program.
Comments in Java
The comments are the notes written inside the code to explain what we are doing. The comment
lines are not executed while we run the program.
Single-line comment:
// This is a comment

Multi-line comment:
/*
This is a multi-line comment.
This is useful for explaining larger sections of code.
*/
To understand Java comments in detail, refer to article: Java Comments
Curly Braces and Indentation in Java
In Java, curly braces {} are used to define blocks of code. For example, the body of a class or
method is enclosed within curly braces.
Example:
if (5 > 2) {

System.out.println("True");
System.out.println("Inside the if block");
}
System.out.println("Outside the if block");
 The two lines inside the if block will run only if the condition is true.
 Indentation is not mandatory, but it is important for readability. And the important point is
Java relies on braces, not spaces for grouping the statements.

Naming Conventions in Java


 Java uses standard naming rules that make the code easier and improves the readability.
 In Java, the class names start with a capital letter for example, HelloWorld. Method and
variable names start with a lowercase letter and use camelCase like printMessage.
 And the constants are written in all uppercase letters with underscores like MAX_SIZE.

Famous Applications Built Using Java


 Android Apps: Most of the Android mobile apps are built using Java.
 Netflix: This uses Java for content delivery and backend services.
 Amazon: Java language is used for its backend systems.
 LinkedIn: This uses Java for handling high traffic and scalability.
 Minecraft: This is one of the world’s most popular games that is built in Java.
 Spotify: This uses Java in parts of its server-side infrastructure.
 Uber: Java is used for backend services like trip management.
 NASA WorldWind: This is a virtual globe software built using Java.

Internal Path Setting


. How to set path of JDK in Windows OS

Setting Temporary Path of JDK

Setting Permanent Path of JDK

How to set path of JDK in Linux OS

The path is required to be set for using tools such as javac, java etc.

If you are saving the java source file inside the jdk/bin directory, path is not required to be set
because all the tools will be available in the current directory.

But If you are having your java file outside the jdk/bin folder, it is necessary to set path of JDK.

There are 2 ways to set java path:

1. temporary
2. permanent

1) To set the temporary path of JDK, you need to follow following steps:

 Open command prompt


 copy the path of jdk/bin directory
 write in command prompt: set path=copied_path

For Example

set path=C:\Program Files\Java\jdk1.6.0_23\bin

Let's see it in the figure given below:


2) For setting the permanent path of JDK, you need to follow these steps:

 Go to MyComputer properties -> advanced tab -> environment variables -> new tab of user
variable -> write path in variable name -> write path of bin folder in variable value -> ok ->
ok -> ok

For Example

1) Go to MyComputer properties

2)Click on advanced tab


3)Click on environment variables

4)click on new tab of user variables


5)write path in variable name

6)Copy the path of bin folder


7)paste path of bin folder in variable value

8)click on ok button
9)click on ok button

Now your permanent path is set. You can now execute any program of java from any drive.
JDK, JRE and JVM
 JDK: Java Development Kit is a software development environment used for developing Java
applications and applets.
 JRE: JRE stands for Java Runtime Environment, and it provides an environment to run only
the Java program onto the system.
 JVM: JVM stands for Java Virtual Machine and is responsible for executing the Java program.
JDK vs JRE vs JVM
Aspect JDK JRE JVM

Used to develop Java Used to run Java


Executes Java bytecode
Purpose applications applications

JVM is OS-specific, but


Platform-dependent Platform-dependent (OS
Platform bytecode is platform-
(OS specific) specific)
Dependency independent

JRE + Development ClassLoader, JIT


JVM + Libraries (e.g.,
tools (javac, debugger, Compiler, Garbage
rt.jar)
Includes etc.) Collector

Writing and compiling Running a Java Convert bytecode into


Use Case Java code application on a system native machine code

Note: The JVM is platform-independent in the sense that the bytecode can run on any machine
with a JVM, but the actual JVM implementation is platform-dependent. Different operating
systems (e.g., Windows, Linux, macOS) require different JVM implementations that interact with
the specific OS and hardware
JDK (Java Development Kit)
The JDK is a software development kit that provides the environment to develop and execute
the java application. It includes two things:
 Development Tools (to provide an environment to develop your java programs)
 JRE (to execute your java program)
Note:
 JDK is only for development (it is not needed for running Java programs)
 JDK is platform-dependent (different version for windows, Linux, macOS)
Working of JDK
The JDK enables the development and execution of Java programs. Consider the following
process:
 Java Source File (e.g., Example.java): You write the Java program in a source file.
 Compilation: The source file is compiled by the Java Compiler (part of JDK) into bytecode,
which is stored in a .class file (e.g., Example.class).
 Execution: The bytecode is executed by the JVM (Java Virtual Machine), which interprets
the bytecode and runs the Java program.

Note: From above, media operation computing during the compile time can be
interpreted.

JRE ((Java Runtime Environment)


The JRE is an installation package that provides an environment to only run(not
develop) the Java program (or application) onto your machine. JRE is only used by those
who only want to run Java programs that are end-users of your system.
Note:
 JRE is only for end-users (not for developers).
 JRE is platform-dependent (different versions for different OS)
Working of JRE
When you run a Java program, the following steps occur:
The following actions occur at runtime as listed below:
 Class Loader
 Byte Code Verifier
 Interpreter
Class Loader: The JRE’s class loader loads the .class file containing the bytecode into
memory.
Bytecode Verifier: JRE includes a bytecode verifier to ensure security before execution
Interpreter: JVM uses an interpreter + JIT compiler to execute bytecode for optimal
performance.

JVM (Java Virtual Machine)

JVM (Java Virtual Machine) runs Java applications as a run-time engine. JVM is the one
that calls the main method present in a Java code. JVM is a part of JRE (Java Runtime
Environment). Java applications are called WORA (Write Once Run Anywhere). This means
a programmer can develop Java code on one system and expect it to run on any other
Java-enabled system without any adjustments. This is all possible because of the JVM.
When we compile a .java file, .class files (containing byte-code) with the same class names
present in the .java file are generated by the Java compiler. This .class file goes through
various steps when we run it. These steps together describe the whole JVM.

Architecture of JVM
The image below demonstrates the architecture and key components of JVM.

Core Components Of JVM


Now, we are going to discuss each component of the JVM in detail.
1. Class Loader Subsystem
It is mainly responsible for three activities.
 Loading
 Linking
 Initialization
1. Loading: The Class loader reads the “.class” file, generate the corresponding binary
data and save it in the method area. For each “.class” file, JVM stores the following
information in the method area.
 The fully qualified name of the loaded class and its immediate parent class.
 Whether the “.class” file is related to Class or Interface or Enum.
 Modifier, Variables and Method information etc.
After loading the “.class” file, JVM creates an object of type Class to represent this file
in the heap memory. Please note that this object is of type lass predefined
in java.lang package. These Class object can be used by the programmer for getting
class level information like the name of the class, parent name, methods and variable
information etc. To get this object reference we can use getClass() method
of Object class.
2. Linking: Performs verification, preparation, and (optionally) resolution.
 Verification: It ensures the correctness of the .class file i.e. it checks whether this
file is properly formatted and generated by a valid compiler or not. If verification
fails, we get run-time exception java.lang.VerifyError. This activity is done by the
component ByteCodeVerifier. Once this activity is completed then the class file is
ready for compilation.
 Preparation: JVM allocates memory for class static variables and initializing the
memory to default values.
 Resolution: It is the process of replacing symbolic references from the type with
direct references. It is done by searching into the method area to locate the
referenced entity.
3. Initialization: In this phase, all static variables are assigned with their values defined
in the code and static block(if any).
2. JVM Memory Areas
 Method area: In the method area, all class level information like class name,
immediate parent class name, methods and variables information etc. are stored,
including static variables.
 Heap area: Information of all objects is stored in the heap area. There is also one Heap
Area per JVM. It is also a shared resource.
 Stack area: For every thread, JVM creates one run-time stack which is stored here.
Every block of this stack is called activation record/stack frame which stores methods
calls. All local variables of that method are stored in their corresponding frame. After a
thread terminates, its run-time stack will be destroyed by JVM. It is not a shared
resource.
 PC Registers: Store address of current execution instruction of a thread. Obviously,
each thread has separate PC Registers.
 Native method stacks: For every thread, a separate native stack is created. It stores
native method information.
3. Execution Engine
Execution engine executes the “.class” (bytecode). It reads the byte-code line by line, uses
data and information present in various memory area and executes instructions. It can be
classified into three parts:
 Interpreter: It interprets the bytecode line by line and then executes.
 Just-In-Time Compiler(JIT): It is used to increase the efficiency of an interpreter. It
compiles the entire bytecode and changes it to native code so whenever the
interpreter sees repeated method calls, JIT provides direct native code for that part so
re-interpretation is not required, thus efficiency is improved.
 Garbage Collector: It destroys un-referenced objects.

5. Java Native Interface (JNI)


It is an interface that interacts with the Native Method Libraries and provides the native
libraries(C, C++) required for the execution. It enables JVM to call C/C++ libraries and to
be called by C/C++ libraries which may be specific to hardware.

Java Data Type Categories


Java has two categories in which data types are segregated
1. Primitive Data Type: These are the basic building blocks that store simple values directly in
memory. Examples of primitive data types are
 boolean
 char
 byte
 short
 int
 long
 float
 double
2. Non-Primitive Data Types (Object Types): These are reference types that store memory
addresses of objects. Examples of Non-primitive data types are
 String
 Array
 Class
 Interface
 Object

1. boolean Data Type


The boolean data type represents a logical value that can be either true or false. Conceptually, it
represents a single bit of information, but the actual size used by the virtual machine is
implementation-dependent and typically at least one byte (eight bits) in practice. Values of the
boolean type are not implicitly or explicitly converted to any other type using casts. However,
programmers can write conversion code if needed.
Syntax:
boolean booleanVar;
Size : Virtual machine dependent (typically 1 byte, 8 bits)
Example: This example, demonstrating how to use boolean data type to display true/false values
// Demonstrating boolean data type
publicclassGeeks {
publicstaticvoidmain(String[] args) {
booleanb1=true;
booleanb2=false;

System.out.println("Is Java fun? "+b1);


System.out.println("Is fish tasty? "+b2);
}
}

Output

Is Java fun? true


Is fish tasty? false

2. byte Data Type


The byte data type is an 8-bit signed two's complement integer. The byte data type is useful for
saving memory in large arrays.
Syntax:
byte byteVar;
Size : 1 byte (8 bits)
Example: This example, demonstrating how to use byte data type to display small integer values.
// Demonstrating byte data type
publicclassGeeks {
publicstaticvoidmain(String[] args) {
bytea=25;
bytet=-10;

System.out.println("Age: "+a);
System.out.println("Temperature: "+t);
}
}

Output
Age: 25
Temperature: -10

3. short Data Type


The short data type is a 16-bit signed two's complement integer. Similar to byte, a short is used
when memory savings matter, especially in large arrays where space is constrained.
Syntax:
short shortVar;
Size : 2 bytes (16 bits)
Example: This example, demonstrates how to use short data type to store moderately small
integer value.
Demonstrating short data types
publicclassGeeks {
publicstaticvoidmain(String[] args) {
shortnum=1000;
shortt=-200;

System.out.println("Number of Students: "+num);


System.out.println("Temperature: "+t);
}
}

Output

Number of Students: 1000


Temperature: -200

4. int Data Type


It is a 32-bit signed two's complement integer.
Syntax:
int intVar;
Size : 4 bytes ( 32 bits )
Remember: In Java SE 8 and later, we can use the int data type to represent an unsigned 32-bit
integer, which has a value in the range [0, 2 32 -1]. Use the Integer class to use the int data type
as an unsigned integer.
Example: This example demonstrates how to use int data type to display larger integer values.
// Demonstrating int data types
publicclassGeeks {
publicstaticvoidmain(String[] args) {
intp=2000000;
intd=150000000;
System.out.println("Population: "+p);
System.out.println("Distance: "+d);
}
}

Output

Population: 2000000
Distance: 150000000

5. long Data Type


The long data type is a 64-bit signed two's complement integer. It is used when an int is not large
enough to hold a value, offering a much broader range.
Syntax:
long longVar;
Size : 8 bytes (64 bits)
Remember: In Java SE 8 and later, you can use the long data type to represent an unsigned 64-bit
long, which has a minimum value of 0 and a maximum value of 2 64 -1. The Long class also
contains methods like comparing Unsigned, divide Unsigned, etc to support arithmetic operations
for unsigned long.
Example: This example demonstrates how to use long data type to store large integer value.
// Demonstrating long data type
publicclassGeeks {
publicstaticvoidmain(String[] args) {
longw=7800000000L;
longl=9460730472580800L;

System.out.println("World Population: "+w);


System.out.println("Light Year Distance: "+l);
}
}

Output

World Population: 7800000000


Light Year Distance: 9460730472580800

6. float Data Type


The float data type is a single-precision 32-bit IEEE 754 floating-point. Use a float (instead of
double) if you need to save memory in large arrays of floating-point numbers. The size of the
float data type is 4 bytes (32 bits).
Syntax:
float floatVar;
Size : 4 bytes (32 bits)
Example: This example demonstrates how to use float data type to store decimal value.
// Demonstrating float data type

publicclassGeeks {
publicstaticvoidmain(String[] args) {
floatpi=3.14f;
floatgravity=9.81f;

System.out.println("Value of Pi: "+pi);


System.out.println("Gravity: "+gravity);
}
}

Output

Value of Pi: 3.14


Gravity: 9.81

7. double Data Type


The double data type is a double-precision 64-bit IEEE 754 floating-point. For decimal values, this
data type is generally the default choice. The size of the double data type is 8 bytes or 64 bits.
Syntax:
double doubleVar;
Size : 8 bytes (64 bits)
Note: Both float and double data types were designed especially for scientific calculations, where
approximation errors are acceptable. If accuracy is the most prior concern then, it is
recommended not to use these data types and use BigDecimal class instead.
It is recommended to go through rounding off errors in java.
Example: This example demonstrates how to use double data type to store precise decimal
value.
// Demonstrating double data type
publicclassGeeks {
publicstaticvoidmain(String[] args) {
doublepi=3.141592653589793;
doublean=6.02214076e23;
System.out.println("Value of Pi: "+pi);
System.out.println("Avogadro's Number: "+an);
}
}

Output

Value of Pi: 3.141592653589793


Avogadro's Number: 6.02214076E23

8. char Data Type


The char data type is a single 16-bit Unicode character with the size of 2 bytes (16 bits).
Syntax:
char charVar;
Size : 2 bytes (16 bits)
Example: This example, demonstrates how to use char data type to store individual characters.
// Demonstrating char data type
publicclassGeeks{
publicstaticvoidmain(String[] args) {
charg='A';
chars='$';

System.out.println("Grade: "+g);
System.out.println("Symbol: "+s);
}
}

Output

Grade: A
Symbol: $

Non-Primitive (Reference) Data Types


1. Strings
Strings are defined as an array of characters. The difference between a character array and a string
in Java is, that the string is designed to hold a sequence of characters in a single variable whereas,
a character array is a collection of separate char-type entities. Unlike C/C++, Java strings are not
terminated with a null character.
Syntax: Declaring a string
<String_Type><string_variable> = “<sequence_of_string>”;
Example: This example demonstrates how to use string variables to store and display text values.
// Demonstrating String data type
publicclassGeeks {
publicstaticvoidmain(String[] args) {
Stringn="Geek1";
Stringm="Hello, World!";

System.out.println("Name: "+n);
System.out.println("Message: "+m);
}
}

Output

Name: Geek1
Message: Hello, World!
Note: String cannot be modified after creation. Use StringBuilder for heavy string manipulation

2. Class
A Class is a user-defined blueprint or prototype from which objects are created. It represents the
set of properties or methods that are common to all objects of one type. In general, class
declarations can include these components, in order:
 Modifiers : A class can be public or has default access. Refer to access specifiers for classes or
interfaces in Java
 Class name: The name should begin with an initial letter (capitalized by convention).
 Superclass(if any): The name of the class's parent (superclass), if any, preceded by the keyword
extends. A class can only extend (subclass) one parent.
 Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any,
preceded by the keyword implements. A class can implement more than one interface.
 Body: The class body is surrounded by braces, { }.
Example: This example demonstrates how to create a class with a constructor and method, and
how to create an object to call the method.
// Demonstrating how to create a class
classCar {
Stringmodel;
intyear;

Car(Stringmodel, intyear) {
this.model=model;
this.year=year;
}
voiddisplay() {
System.out.println(model+""+year);
}
}

publicclassGeeks {
publicstaticvoidmain(String[] args) {
CarmyCar=newCar("Toyota", 2020);
myCar.display();
}
}

Output

Toyota 2020

3. Object
An Object is a basic unit of Object-Oriented Programming and represents real-life entities. A
typical Java program creates many objects, which as you know, interact by invoking methods. An
object consists of :
 State: It is represented by the attributes of an object. It also reflects the properties of an
object.
 Behavior: It is represented by the methods of an object. It also reflects the response of an
object to other objects.
 Identity: It gives a unique name to an object and enables one object to interact with other
objects.
Example: This example demonstrates how to create the object of a class.
//Define the Car class

classCar {
Stringmodel;
intyear;

// Constructor to initialize the Car object


Car(Stringmodel, intyear) {
this.model=model;
this.year=year;
}
}

// Main class to demonstrate object creation


publicclassGeeks {
publicstaticvoidmain(String[] args) {
// Create an object of the Car class
CarmyCar=newCar("Honda", 2021);

// Access and print the object's properties


System.out.println("Car Model: "+myCar.model);
System.out.println("Car Year: "+myCar.year);
}
}

Output

Car Model: Honda


Car Year: 2021

4. Interface
Like a class, an interface can have methods and variables, but the methods declared in an
interface are by default abstract (only method signature, no body).
 Interfaces specify what a class must do and not how. It is the blueprint of the class.
 An Interface is about capabilities like a Player may be an interface and any class implementing
Player must be able to (or must implement) move(). So it specifies a set of methods that the
class has to implement.
 If a class implements an interface and does not provide method bodies for all functions
specified in the interface, then the class must be declared abstract.
 A Java library example is Comparator Interface. If a class implements this interface, then it can
be used to sort a collection.
Example: This example demonstrates how to implement an interface.
// Demonstrating the working of interface
interfaceAnimal {
voidsound();
}

classDogimplementsAnimal {
publicvoidsound() {
System.out.println("Woof");
}
}

publicclassInterfaceExample {
publicstaticvoidmain(String[] args) {
DogmyDog=newDog();
myDog.sound();
}
}

Output

Woof

5. Array
An Array is a group of like-typed variables that are referred to by a common name. Arrays in Java
work differently than they do in C/C++. The following are some important points about Java
arrays.
 In Java, all arrays are dynamically allocated. (discussed below)
 Since arrays are objects in Java, we can find their length using member length. This is different
from C/C++ where we find length using size.
 A Java array variable can also be declared like other variables with [] after the data type.
 The variables in the array are ordered and each has an index beginning with 0.
 Java array can also be used as a static field, a local variable, or a method parameter.
 The size of an array must be specified by an int value and not long or short.
 The direct superclass of an array type is Object.
 Every array type implements the interfaces Cloneable and java.io.Serializable.
Example: This example demonstrates how to create and access elements of an array.
Demonstrating how to create an array
publicclassGeeks {
publicstaticvoidmain(String[] args) {
int[] num= {1, 2, 3, 4, 5};
String[] arr= {"Geek1", "Geek2", "Geek3"};

System.out.println("First Number: "+num[0]);


System.out.println("Second Fruit: "+arr[1]);
}
}

Output

First Number: 1
Second Fruit: Geek2

Unicode System

Unicode is a standard encoding system that assigns a unique numeric value to every
character, regardless of the platform, program, or language. It allows computers to
represent and manipulate text from different writing systems, including alphabets,
ideographs, and symbols.

Once we have the code point, we can use Java's char data type and the escape sequence '\
u' to represent the Unicode character. In the “\uxxxx” notation, “xxxx” is the character's
code point in the hexadecimal representation. For example, the hexadecimal ASCII code of
'A' is 41 (decimal: 65).

OPERATORS IN JAVA

Java provides a rich set of operators to manipulate variables. We can divide all the Java

operators into the following groups:


 ArithmeticOperators
 RelationalOperators
 BitwiseOperators
 LogicalOperators
 IncrementorDecrement operators
 ConditionalOperators
 Assignment Operators
 SpecialOperators
TheArithmeticOperators:

Arithmetic operators are used in mathematical expressions in the same way that they
are used in algebra. The following table lists the arithmetic operators:

AssumeintegervariableAholds10andvariableBholds20,then: Show

Examples
SL.NO Operatorand Example

1 +( Addition)
Addsvaluesoneithersideoftheoperator
Example:A+Bwillgive30

2 -(Subtraction )
Subtractsrighthandoperandfromlefthandoperand
Example:A-Bwillgive-10
3 *(Multiplication)

TheRelationalOperators:

TherearefollowingrelationaloperatorssupportedbyJavalangua

ge Assume variable A holds 10 and variable B holds 20, then:

SR.NO Operatorand Description

1 ==(equalto)
Checksifthevaluesoftwooperandsareequalornot,ifyesthenconditionbecomestru
e.
Example:(A==B) isnottrue.
2 !=(notequalto)
Checksifthevaluesoftwooperandsareequalornot,ifvaluesarenotequalthen
condition becomes true.
Example:(A!=B) is true.
3 >(greaterthan)
Checks if the value of left operand is greater than the value of right operand, if
yes then condition becomes true.
Example:(A>B) isnot true.
4 <(lessthan)
Checksifthevalueofleftoperandislessthanthevalueofrightoperand,ifyesthen
condition becomes true.
Example:(A<B) is true.
5 >=(greaterthanorequalto)
Checks if the value of leftoperand isgreaterthan orequal to the value of right
operand, if yes then condition becomes true.
Example(A>=B) isnot true.
6 <=(lessthanorequalto)
Checks if the value of left operand is less than or equal to the value of right
operand, if yes then condition becomes true.
example(A<=B) istrue.
The Bitwise Operators:

Java defines several bitwise operators, which can be applied to the integer types, long,
int, short,char, and byte.
Bitwiseoperatorworksonbitsandperformsbit-by-
bitoperation.Assumeifa=60;andb=13;now in binary format they will be as follows:
a =00111100
b=00001101
a&b=00001100
a|b=00111101
a^b=00110001
~a=11000011
Thefollowingtableliststhe bitwiseoperators:
AssumeintegervariableAholds60andvariableBholds13then:

SR.NO Operatorand Description

1 & (bitwiseand)
BinaryANDOperatorcopiesabittotheresultifitexistsinboth operands.
Example:(A&B)willgive 12whichis00001100

2 |(bitwiseor)
BinaryOROperatorcopiesabit ifitexistsineitheroperand.
Example:(A|B)willgive 61whichis00111101

3 ^(bitwiseXOR)
BinaryXOROperatorcopiesthebitifitissetinone operandbutnotboth.
Example:(A^B) willgive49whichis00110001

4 ~(bitwisecompliment)
BinaryOnesComplementOperatorisunaryandhastheeffectof'flipping'bits.
Example:(~A)willgive-61whichis11000011in2'scomplementformduetoasigned binary
number.
5 <<(leftshift)
BinaryLeftShiftOperator.Theleftoperandsvalueismovedleftbythenumberofbits
specified by the right operand
Example:A<<2willgive240whichis11110000
6 >>(rightshift)
BinaryRightShiftOperator.Theleftoperandsvalueismovedrightby thenumber ofbits
specified by the right operand.
Example:A>>2willgive15whichis1111
The Logical Operators: The following table lists the logical operators:

Assume Boolean variables A holds true and variable B holds false,

then: Show Examples

Operator Description

1 &&(logical and)
Called Logical AND operator. If both the operands are non-zero, then the condition
becomes true.
Example(A&&B) is false.

2 ||(logicalor)
CalledLogicalOROperator.Ifanyofthetwooperandsarenon-zero,thenthe condition
becomes true.
Example(A|| B) is true.

3 !(logical not)
CalledLogicalNOTOperator.Usetoreversesthelogicalstateofitsoperand.Ifa condition is
true then Logical NOT operator will make false.
Example!(A&&B) is true.

Increment or Decrement operator

1 ++(Increment)
Increasesthevalueofoperandby1
Example:B++gives21

2 --(Decrement )
Decreasesthevalueofoperandby1
Example:B--gives 19
The Assignment Operators:

Therearefollowing assignmentoperatorssupportedbyJavalanguage:

Show Examples
SR.NO Operatorand Description

1 =Simpleassignmentoperator,Assignsvaluesfromrightside operandstoleftside operand.


Example:C =A+Bwill assignvalueofA+BintoC

2 += Add AND assignment operator, It adds right operand to the left operand and assign
theresult to left operand.
Example:C+=Ais equivalenttoC=C+A

3 -= Subtract AND assignment operator, It subtracts right operand from the left operand and
assign the result to left operand.
Example:C -=Ais equivalent toC=C– A

4 *= Multiply AND assignment operator, It multiplies right operand with the left operand and
assign the result to left operand.
Example:C*=Ais equivalent toC=C*A

5 /=DivideANDassignmentoperator,Itdividesleftoperandwiththerightoperandandassign the
result to left operand
ExampleC/=Ais equivalent toC=C/A
Conditional Operator(?:)

Conditionaloperatorisalsoknownastheternaryoperator.Thisoperatorconsistsofthreeope
rands
andisusedtoevaluateBooleanexpressions.Thegoaloftheoperatoristodecidewhichvaluesh
variablex=(expression)? value iftrue:valueiffalse
ould be assigned to the variable. The operator is written as:
Followingistheexample: public
class Test

publicstaticvoidmain(Stringargs[])
{

inta,b;
a=10;
b=(a==1)?20:30;
System.out.println("Valueofbis:"+b);
b = (a == 10) ? 20: 30;
System.out.println("Value ofbis: "+b);
}

Thiswouldproducethefollowingresult−

Valueofb is :30
Valueofb is :20

Special Operator instance of Operator:


Thisoperatorisusedonlyforobjectreferencevariables.The

operatorcheckswhethertheobjectis of a particular type (class type or interface type).

Instance of operator is written as:


(Objectreferencevariable)instanceof(class/interface type)

Ifthe objectreferredbythe variable on theleftside ofthe operatorpassesthe IS-Acheckforthe

class/interface type on the right side, then the result will be true.
Followingistheexample:
publicclassTest{

publicstaticvoidmain(Stringargs[])
{ String name = "James";
//followingwillreturntruesincenameistypeofString
boolean result = name instanceof String;
System.out.println( result );
}

Thiswouldproducethefollowing result:
true
This operator will still return true if the object beingcompared is the assignment
compatible with the type on the right. Following is one more example:
classVehicle {}

public class Car extends Vehicle


{
publicstaticvoidmain(Stringargs[])
{
Vehiclea=newCar();
booleanresult=ainstanceofCar;
System.out.println( result );
}

Thiswouldproduce
true
JAVA KEYWORDS

In Java, keywords are the reserved words that have some predefined meanings and are used by
the Java compiler for some internal process or represent some predefined actions. These words
cannot be used as identifiers such as variable names, method names, class names, or object
names.
Now, let us go through a simple example before a deep dive into the article.

Example:
Program to demonstrate Keywords
class Hello {

public static void main(String[] args)


{
// Using final and int keyword
final int x = 10;

// Using if and else keywords


if(x > 10){
System.out.println("Failed");
}
else {
System.out.println("Successful demonstration"
+" of keywords.");
}
}
}

Output
Successful demonstration of keywords.
Java Keywords List
Java contains a list of keywords or reserved words which are also highlighted with different
colors be it an IDE or editor in order to segregate the differences between flexible words and
reserved words. As of Java 21, there are 53 keywords defined in Java. They are listed below in
the table with the primary action associated with them.
Keywords Usage

Specifies that a class or method will be


abstract
implemented later, in a subclass
Keywords Usage

Assert describes a predicate placed in a


Java program to indicate that the
assert
developer thinks that the predicate is
always true at that place.

A data type that can hold True and False


boolean
values only

A control statement for breaking out of


break
loops.

A data type that can hold 8-bit data


byte
values

Used in switch statements to mark


case
blocks of text

Catches exceptions generated by try


catch
statements

Decision-making statements in Java execute a block of code based on a condition.


Decision-making in programming is similar to decision-making in real life. In programming, we
also face situations where we want a certain block of code to be executed when some condition
is fulfilled.
A programming language uses control statements to control the flow of execution of a program
based on certain conditions. These are used to cause the flow of execution to advance and
branch based on changes to the state of a program. Java provides several control statements to
manage program flow, including:
 Conditional Statements: if, if-else, nested-if, if-else-if
 Switch-Case: For multiple fixed-value checks
 Jump Statements: break, continue, return
The table below demonstrates various control flow statements in programming, their use cases,
and examples of their syntax.
Statement Use Case Example

if Single condition check if (age >= 18)


Statement Use Case Example

if-else Two-way decision if (x > y) {...} else {...}

nested-if Multi-level conditions if (x > 10) { if (y > 5) {...} }

if-else-if Multiple conditions if (marks >= 90) {...} else if (marks >= 80) {...}

switch-case Exact value matching switch (day) { case 1: ... }

break Exit loop/switch break;

continue Skip iteration continue;

return Exit method return result;

1. Java if Statement
The if statement is the most simple decision-making statement. It is used to decide whether a
certain statement or block of statements will be executed or not i.e. if a certain condition is true
then a block of statements is executed otherwise not.
Syntax:
if(condition) {
// Statements to execute if
// condition is true
}
Here, the condition after evaluation will be either true or false. if statement accepts boolean
values - if the value is true then it will execute the block of statements under it. If we don't use
curly braces( {} ), only the next line after the if is considered as part of the if block For example,
if (condition) // Assume condition is true
statement1; // Belongs to the if block
statement2; // Does NOT belong to the if block
Here's what happens:
 If the condition is True statement1 executes.
 statement2 runs no matter what because it's not a part of the if block
if Statement Execution Flow
The below diagram demonstrates the flow chart of an "if Statement execution flow" in
programming.
Example: The below Java program demonstrates without curly braces, only the first line after the
if statement is part of the if block and the rest code will be execute independently.
// Java program to illustrate
// if statement without curly block
importjava.util.*;

classHello {
publicstaticvoidmain(Stringargs[])
{
inti=10;

if (i<15)

// part of if block(immediate one statement


// after if condition)
System.out.println("Inside If block");

// always executes as it is outside of if block


System.out.println("10 is less than 15");

// This statement will be executed


// as if considers one statement by default again
// below statement is outside of if block
System.out.println("I am Not in if");
}
}
Output

Inside If block
10 is less than 15
I am Not in if

2. Java if-else Statement


The if statement alone tells us that if a condition is true it will execute a block of statements and
if the condition is false it won't. But what if we want to do something else if the condition is
false? Here, comes the "else" statement. We can use the else statement with the if statement to
execute a block of code when the condition is false.
Syntax:
if(condition){
// Executes this block if
// condition is true
}else{
// Executes this block if
// condition is false
}
if-else Statement Execution flow
The below diagram demonstrates the flow chart of an "if-else Statement execution flow" in
programming
Example: The below Java program demonstrates the use of if-else statement to execute
different blocks of code based on the condition.
// Java program to demonstrate
// the working of if-else statement
importjava.util.*;

classHello {
publicstaticvoidmain(Stringargs[])
{
inti=10;

if (i<15)
System.out.println("i is smaller than 15");
else
System.out.println("i is greater than 15");
}
}

Output

i is smaller than 15

3. Java nested-if Statement


A nested if is an if statement that is the target of another if or else. Nested if statements mean
an if statement inside an if statement. Yes, java allows us to nest if statements within if
statements. i.e, we can place an if statement inside another if statement.
Syntax:
if (condition1) {
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}
nested-if Statement Execution Flow
The below diagram demonstrates the flow chart of an "nested-if Statement execution flow" in
programming.
Example: The below Java program demonstrates the use of nested if statements to check
multiple conditions.
Java program to demonstrate the
// working of nested-if statement
importjava.util.*;

classHello {
publicstaticvoidmain(Stringargs[])
{
inti=10;

if (i==10||i<15) {

// First if statement
if (i<15)
{
System.out.println("i is smaller than 15");

// Nested - if statement
// Will only be executed if statement above
// it is true
if (i<12)
System.out.println( "i is smaller than 12 too");

else {
System.out.println("i is greater than 15");
}
}
}
}
Output

i is smaller than 15
i is smaller than 12 too

4. Java if-else-if ladder


Here, a user can decide among multiple options.The if statements are executed from the top
down. As soon as one of the conditions controlling the if is true, the statement associated with
that 'if' is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then
the final else statement will be executed. There can be as many as 'else if' blocks associated with
one 'if' block but only one 'else' block is allowed with one 'if' block.
Syntax:
if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition2 is true
} else {
// code to be executed if all conditions are false
}
if-else-if ladder Execution Flow
The below diagram demonstrates the flow chart of an "if-else-if ladder execution flow" in
programming
Example: This example demonstrates an if-else-if ladder to check multiple conditions and
execute the corresponding block of code based on the value of I.
// Java program to demonstrate the
// working of if-else-if ladder
importjava.util.*;

classHello {
publicstaticvoidmain(Stringargs[])
{
inti=20;

if (i==10)
System.out.println("i is 10");
elseif (i==15)
System.out.println("i is 15");
elseif (i==20)
System.out.println("i is 20");
else
System.out.println("i is not present");
}
}

Output

i is 20

5. Java Switch Case


The switch statement is a multiway branch statement. It provides an easy way to dispatch
execution to different parts of code based on the value of the expression.
Syntax:
switch (expression) {
case value1:
// code to be executed if expression == value1
break;
case value2:
// code to be executed if expression == value2
break;
// more cases...
default:
// code to be executed if no cases match
}
switch Statements Execution Flow
The below diagram demonstrates the flow chart of a "switch Statements execution flow" in
programming.

Example: The below Java program demonstrates the use of switch-case statement to evaluate
multiple fixed values.
Java program to demonstrates the
// working of switch statements
importjava.io.*;

classSwitchcase {
publicstaticvoidmain(String[] args)
{
intnum=20;
switch (num) {
case5:
System.out.println("It is 5");
break;
case10:
System.out.println("It is 10");
break;
case15:
System.out.println("It is 15");
break;
case20:
System.out.println("It is 20");
break;
default:
System.out.println("Not present");
}
}
}

Output

It is 20
 The expression can be of type byte, short, int char, or an enumeration. Beginning with JDK7,
the expression can also be of type String.
 Duplicate case values are not allowed.
 The default statement is optional.
 The break statement is used inside the switch to terminate a statement sequence.
 The break statements are necessary without the break keyword, statements in switch blocks
fall through.
 If the break keyword is omitted, execution will continue to the next case.

6. jump Statements
Java supports three jump statements: break, continue and return. These three statements
transfer control to another part of the program.
 Break: In Java, a break is majorly used for:

o Terminate a sequence in a switch statement (discussed above).


o To exit a loop.
o Used as a "civilized" form of goto.
 Continue: Sometimes it is useful to force an early iteration of a loop. That is, you might want
to continue running the loop but stop processing the remainder of the code in its body for
this particular iteration. This is, in effect, a goto just past the body of the loop, to the loop's
end. The continue statement performs such an action.
Jump Statements Execution Flow
The below diagram demonstrates the flow chart of a "jump Statements execution flow" in
programming.

Example: The below Java Program demonstrates how the continue statement skip the current
iteration when a condition is true.
//Java program to demonstrates the use of
// continue in an if statement
importjava.util.*;
classStatement {
publicstaticvoidmain(Stringargs[])
{
for (inti=0; i<10; i++) {
// If the number is even
// skip and continue
if (i%2==0)
continue;
// If number is odd, print it
System.out.print(i+"");
}
}
}

Output

13579

Return Statement
The return statement is used to explicitly return from a method. That is, it causes program
control to transfer back to the caller of the method.
Example: The below Java program demonstrates how the return statements stop a method and
skips the rest of the code.
// Java program to demonstrate the use of return
importjava.util.*;

publicclassStatement {
publicstaticvoidmain(Stringargs[])
{
booleant=true;
System.out.println("Before the return.");

if (t)
return;

// Compiler will bypass every statement


// after return
System.out.println("This won't execute.");
}
}

Output
Before the return.

Java Classes/Objects
Java is an object-oriented programming language.

Everything in Java is associated with classes and objects, along with its attributes and methods. For
example: in real life, a car is an object. The car has attributes, such as weight and color,
and methods, such as drive and brake.

A Class is like an object constructor, or a "blueprint" for creating objects

Create a Class

To create a class, use the keyword class:

Main.java

Create a class named "Main" with a variable x:

public class Main {

int x = 5;

Create an Object

In Java, an object is created from a class. We have already created the class named Main, so now
we can use this to create objects.

To create an object of Main, specify the class name, followed by the object name, and use the
keyword new:

Example

Create an object called "myObj" and print the value of x:

public class Main {

int x = 5;

public static void main(String[] args) {

Main myObj = new Main();

System.out.println(myObj.x);

}
Java Class Methods

Create a method named myMethod() in Main:

myMethod() prints a text (the action), when it is called. To call a method, write the method's name
followed by two parentheses () and a semicolon;

Example

Inside main, call myMethod():

public class Main {

static void myMethod() {

System.out.println("Hello World!");

public static void main(String[] args) {

myMethod();

// Outputs "Hello World!"

Static vs. Public

In the example above, we created a static method, which means that it can be accessed without
creating an object of the class, unlike public, which can only be accessed by objects:

Example

An example to demonstrate the differences between static and public methods:

public class Main {

// Static method

static void myStaticMethod() {

System.out.println("Static methods can be called without creating objects");


}

// Public method

public void myPublicMethod() {

System.out.println("Public methods must be called by creating objects");

// Main method

public static void main(String[] args) {

myStaticMethod(); // Call the static method

// myPublicMethod(); This would compile an error

Main myObj = new Main(); // Create an object of Main

myObj.myPublicMethod(); // Call the public method on the object

Method in Java

A method is a block of code which only runs when it is called.

You can pass data, known as parameters, into a method.

Methods are used to perform certain actions, and they are also known as functions.

Why use methods? To reuse code: define the code once, and use it many times.

Create a Method

A method must be declared within a class. It is defined with the name of the method, followed by
parentheses (). Java provides some pre-defined methods, such as System.out.println(), but you can
also create your own methods to perform certain actions:

Example

Create a method inside Main:


public class Main {

static void myMethod() {

// code to be executed

Example Explained

 myMethod() is the name of the method


 static means that the method belongs to the Main class and not an object of the Main class.
You will learn more about objects and how to access methods through objects later in this
tutorial.
 void means that this method does not have a return value. You will learn more about return
values later in this chapter

Call a Method

To call a method in Java, write the method's name followed by two parentheses () and a
semicolon;

In the following example, myMethod() is used to print a text (the action), when it is called:

Example

Inside main, call the myMethod() method:

public class Main {

static void myMethod() {

System.out.println("I just got executed!");

public static void main(String[] args) {

myMethod();

}
// Outputs "I just got executed!"

A method can also be called multiple times:

Example

public class Main {

static void myMethod() {

System.out.println("I just got executed!");

public static void main(String[] args) {

myMethod();

myMethod();

myMethod();

// I just got executed!

// I just got executed!

// I just got executed!

Parameters and Arguments

Information can be passed to methods as a parameter. Parameters act as variables inside the
method.

Parameters are specified after the method name, inside the parentheses. You can add as many
parameters as you want, just separate them with a comma.

The following example has a method that takes a String called fname as parameter. When the
method is called, we pass along a first name, which is used inside the method to print the full
name:

public class Main {


static void myMethod(String fname) {

System.out.println(fname + " Refsnes");

public static void main(String[] args) {

myMethod("Liam");

myMethod("Jenny");

myMethod("Anja");

// Liam Refsnes

// Jenny Refsnes

// Anja Refsnes

When a parameter is passed to the method, it is called an argument. So, from the example
above: fname is a parameter, while Liam, Jenny and Anja are arguments.

Multiple Parameters

You can have as many parameters as you like:

Example

public class Main {

static void myMethod(String fname, int age) {

System.out.println(fname + " is " + age);

public static void main(String[] args) {


myMethod("Liam", 5);

myMethod("Jenny", 8);

myMethod("Anja", 31);

// Liam is 5

// Jenny is 8

// Anja is 31

Java Constructors

A constructor in Java is a special method that is used to initialize objects.

The constructor is called when an object of a class is created.

It can be used to set initial values for object attributes:

Create a constructor:

// Create a Main class

public class Main {

int x; // Create a class attribute

// Create a class constructor for the Main class

public Main() {

x = 5; // Set the initial value for the class attribute x

public static void main(String[] args) {

Main myObj = new Main(); // Create an object of class Main (This will call the constructor)

System.out.println(myObj.x); // Print the value of x


}

// Outputs 5

Constructor Parameters

Constructors can also take parameters, which is used to initialize attributes.

The following example adds an int y parameter to the constructor. Inside the constructor we set x
to y (x=y). When we call the constructor, we pass a parameter to the constructor (5), which will set
the value of x to 5:

Example

public class Main {

int x;

public Main(int y) {

x = y;

public static void main(String[] args) {

Main myObj = new Main(5);

System.out.println(myObj.x);

Types of Constructor

In Java, constructors can be divided into three types:

No-Arg Constructor

Parameterized Constructor

Default Constructor

1. Java No-Arg Constructors


Similar to methods, a Java constructor may or may not have any parameters (arguments).

If a constructor does not accept any parameters, it is known as a no-argument constructor. For
example,

private Constructor() {

// body of the constructor

Example: Java Private No-arg Constructor

class Main {

int i;

// constructor with no parameter

private Main() {

i = 5;

System.out.println("Constructor is called");

public static void main(String[] args) {

// calling the constructor without any parameter

Main obj = new Main();

System.out.println("Value of i: " + obj.i);

Output:

Constructor is called

Value of i: 5

In the above example, we have created a constructor Main().


Here, the constructor does not accept any parameters. Hence, it is known as a no-arg constructor.
Notice that we have declared the constructor as private.
Once a constructor is declared private, it cannot be accessed from outside the class.
So, creating objects from outside the class is prohibited using the private constructor.

Here, we are creating the object inside the same class.

However, if we want to create objects outside the class, then we need to declare the constructor
as public.
Example: Java Public no-arg Constructors

class Company {

String name;

// public constructor

public Company() {

name = "Programiz";

class Main {

public static void main(String[] args) {

// object is created in another class

Company obj = new Company();

System.out.println("Company name = " + obj.name);

Output

Company name = Programiz

2. Java Parameterized Constructor


A Java constructor can also accept one or more parameters. Such constructors are known as
parameterized constructors (constructors with parameters).

Example: Parameterized Constructor


class Main {

String languages;

// constructor accepting single value

Main(String lang) {

languages = lang;

System.out.println(languages + " Programming Language");

public static void main(String[] args) {

// call constructor by passing a single value

Main obj1 = new Main("Java");

Main obj2 = new Main("Python");

Main obj3 = new Main("C");

Output

Java Programming Language

Python Programming Language

C Programming Language

In the above example, we have created a constructor named Main().


Here, the constructor takes a single parameter. Notice the expression:

Main obj1 = new Main("Java");

Here, we are passing the single value to the constructor.

Based on the argument passed, the language variable is initialized inside the constructor.

3. Java Default Constructor

If we do not create any constructor, the Java compiler automatically creates a no-arg constructor
during the execution of the program.

This constructor is called the default constructor.

Example: Default Constructor


class Main {

int a;

boolean b;

public static void main(String[] args) {

// calls default constructor

Main obj = new Main();

System.out.println("Default Value:");

System.out.println("a = " + obj.a);

System.out.println("b = " + obj.b);

Output

Default Value:
a=0

b = false

Access Modifiers

In Java, access modifiers are used to set the accessibility (visibility)


of classes, interfaces, variables, methods, constructors, data members, and the setter methods.
For example,

class College {

public void method1() {...}

private void method2() {...}

Types of Access Modifier

There are four access modifiers keywords in Java and they are:

Default Access Modifier

If we do not explicitly specify any access modifier for classes, methods, variables, etc, then by

default the default access modifier is considered. For example,

package defaultPackage;

class Logger {

void message(){

System.out.println("This is a message");

}
Here, the Logger class has the default access modifier. And the class is visible to all the classes that

belong to the defaultPackage package. However, if we try to use the Logger class in another class

outside of defaultPackage, we will get a compilation error.

Private Access Modifier

When variables and methods are declared private, they cannot be accessed outside of the class.

For example,
class Data {

// private variable

private String name;

public class Main {

public static void main(String[] main){

// create an object of Data

Data d = new Data();

// access private variable and field from another class

d.name = "Program";

In the above example, we have declared a private variable named name. When we run the
program, we will get the following error:

Main.java:18: error: name has private access in Data

d.name = "Program";

^
The error is generated because we are trying to access the private variable of the Data class from
the Main class.

You might be wondering what if we need to access those private variables. In this case, we can use
the getters and setters method. For example,

class Data {

private String name;

// getter method

public String getName() {

return this.name;

// setter method

public void setName(String name) {

this.name= name;

public class Main {

public static void main(String[] main){

Data d = new Data();

// access the private variable using the getter and setter

d.setName("Program");

System.out.println(d.getName());

Output:

Program
In the above example, we have a private variable named name. In order to access the variable
from the outer class, we have used methods: getName() and setName(). These methods are called
getter and setter in Java.

Here, we have used the setter method (setName()) to assign value to the variable and the getter
method (getName()) to access the variable.

Protected Access Modifier

When methods and data members are declared protected, we can access them within the same
package as well as from subclasses. For example,

class College {

// protected method

protected void display() {

System.out.println("I am in college");

class Student extends College {

public static void main(String[] args) {

// create an object of Student class

Studentstud = new Student();

// access protected method

stud.display();

Output:

I am in college
In the above example, we have a protected method named display() inside the College class.

The College class is inherited by the Student class.

We then created an object stud of the Student class. Using the object we tried to access the

protected method of the parent class.

Since protected methods can be accessed from the child classes, we are able to access the method

of Collegeclass from the Student class.

Public Access Modifier

When methods, variables, classes, and so on are declared public, then we can access them from
anywhere. The public access modifier has no scope restriction. For example,

// College.java file

// public class

public class College {

// public variable

public int Count;

// public method

public void display() {

System.out.println("I am inCollege.");

System.out.println("we have " + Count + " student.");

// Main.java
public class Main {

public static void main( String[] args ) {

// accessing the public class

College c = new College();

// accessing the public variable

c.Count = 40;

// accessing the public method

c.display();

Output:

I am inCollege.

we have 40student.

Here,

The public class College is accessed from the Main class.

The public variable Count is accessed from the Main class.

The public method display() is accessed from the Main class

static Keyword

The static keyword is used to indicate that a particular member belongs to the class itself rather
than to any specific instance of the class. This means that the static member is shared across all
instances of the class.

Syntax

static dataType variableName;


static returnType methodName() {

// method body

Example: Static Variable and Method

public class StaticExample {

static int counter = 0;

static void incrementCounter() {

counter++;

public static void main(String[] args) {

incrementCounter();

System.out.println("Counter: " + StaticExample.counter);

In this example, counter is a static variable, and incrementCounter is a static method. Both can be
accessed without creating an instance of StaticExample.

Final Keyword

The final keyword is used to declare constants, prevent method overriding, and restrict
inheritance.

Usage

Final Variables: Once assigned, their value cannot be changed.

Final Methods: Cannot be overridden by subclasses.

Final Classes: Cannot be subclassed.

Syntax
final dataType variableName = value;

final returnType methodName() {

// method body

final class ClassName {

// class body

Ex:

final class Main {

final void display() {

System.out.println("This is a final method.");

public static void main(String[] args) {

Main obj = new Main();

obj.display();

String Manipulation

1. Common String Methods

Length: Returns the length of the string.

String str = "Hello, World!";

int length = str.length(); // length is 13

Concatenation: Combines two strings.

String str1 = "Hello, ";


String str2 = "World!";

String combined = str1.concat(str2); // combined is "Hello, World!"

UpperCase/LowerCase: Converts all characters in the string to upper case or lower case.

String lower = str.toLowerCase(); // lower is "hello, world!"

String upper = str.toUpperCase(); // upper is "HELLO, WORLD!"

Substring: Extracts a substring from the string.

String sub = str.substring(7); // sub is "World!"

Replace: Replaces occurrences of a character or a substring.

String replaced = str.replace('l', 'p'); // replaced is "Heplo, Worpd!"

IndexOf/LastIndexOf: Returns the position of a character or substring.

int index = str.indexOf('W'); // index is 7

Trim: Removes whitespace from both ends of the string.

String trimmed = " Hello World! ".trim(); // trimmed is "Hello World!"

2. String Comparison

equals: Compares two strings for content equality.

boolean isEqual = "Hello".equals("hello"); // isEqual is false

equalsIgnoreCase: Compares two strings, ignoring case differences.

boolean isCaseIgnored = "Hello".equalsIgnoreCase("hello"); // isCaseIgnored is true

3. String Conversion

valueOf: Converts different types of values into strings.

String numStr = String.valueOf(123); // numStr is "123"

Java Arrays

An array is a collection of similar types of data.

For example, if we want to store the names of 100 people then we can create an array of the
string type that can store 100 names.
String[] array = new String[100];

Here, the above array cannot store more than 100 names. The number of values in a Java array is
always fixed.

How to declare an array in Java?

In Java, here is how we can declare an array.

dataType[] arrayName;

 dataType - it can be primitive data types like int, char, double, byte, etc. or Java objects

 arrayName - it is an identifier

For example,

double[] data;

Here, data is an array that can hold values of type double.

To define the number of elements that an array can hold, we have to allocate memory for the
array in Java. For example,

// declare an array

double[] data;

// allocate memory

data = new double[10];

Here, the array can store 10 elements. We can also say that the size or length of the array is 10.

In Java, we can declare and allocate the memory of an array in one single statement. For example,

double[] data = new double[10];

Initialize Arrays in Java

In Java, we can initialize arrays during declaration. For example,

//declare and initialize and array

int[] age = {12, 4, 5, 2, 5};

Here, we have created an array named age and initialized it with the values inside the curly
brackets.
Note that we have not provided the size of the array. In this case, the Java compiler automatically
specifies the size by counting the number of elements in the array (i.e. 5).

In the Java array, each memory location is associated with a number. The number is known as an
array index. We can also initialize arrays in Java, using the index number. For example,

// declare an array

int[] age = new int[5];

// initialize array

age[0] = 12;

age[1] = 4;

age[2] = 5;

..

Java Arrays initialization

Note:

 Array indices always start from 0. That is, the first element of an array is at index 0.

 If the size of an array is n, then the last element of the array will be at index n-1.

How to Access Elements of an Array in Java?

We can access the element of an array using the index number. Here is the syntax for accessing
elements of an array,

// access array elements

array[index]

Let's see an example of accessing array elements using index numbers.

Example: Access Array Elements


class Main {

public static void main(String[] args) {

// create an array

int[] age = {12, 4, 5, 2, 5};

// access each array elements

System.out.println("Accessing Elements of Array:");

System.out.println("First Element: " + age[0]);

System.out.println("Second Element: " + age[1]);

System.out.println("Third Element: " + age[2]);

System.out.println("Fourth Element: " + age[3]);

System.out.println("Fifth Element: " + age[4]);

Output

Accessing Elements of Array:

First Element: 12

Second Element: 4

Third Element: 5

Fourth Element: 2

Fifth Element: 5

In the above example, notice that we are using the index number to access each element of the
array.

We can use loops to access all the elements of the array at once.

Looping Through Array Elements

In Java, we can also loop through each element of the array. For example,
Example: Using For Loop

class Main {

public static void main(String[] args) {

// create an array

int[] age = {12, 4, 5};

// loop through the array

// using for loop

System.out.println("Using for Loop:");

for(int i = 0; i < age.length; i++) {

System.out.println(age[i]);

Output

Using for Loop:

12

In the above example, we are using the for Loop in Java to iterate through each element of the
array. Notice the expression inside the loop,

age.length

Here, we are using the length property of the array to get the size of the array.

Multidimensional Arrays

Arrays we have mentioned till now are called one-dimensional arrays. However, we can declare
multidimensional arrays in Java.
A multidimensional array is an array of arrays. That is, each element of a multidimensional array is
an array itself. For example,

int[][] matrix = {{1, 4, 4}, {4, 1, 3}};

Here, we have created a multidimensional array named matrix. It is a 2-dimensional array.

LOOPINGSTATEMENTS [5Marks]

The iteration statements allow a set of instructions to be performed repeatedly until a certain
condition is fulfilled. The iteration statements are also called loops or looping statements. Java
provides three kinds of loops: while loop, do-while loop, and for loop.

A Computer is used for performing many Repetitive types of tasks The Process of Repeatedly
performing tasks is known as looping

InTheloopgenerallytherearethreebasicoperationsareperformed
1) Initialization
2) Conditioncheck
3) Increment

Therearethethreetypesofloopsinthejava

1) while
2) do-while
3) for

alltheseare usedforperformingthe repetitivetasksuntilthegivencondition isnot true.

While

While Loop is Known as Entry Controlled Loop because in The while loop first we initialize
the value of variable or Starting point of Execution and then we check the condition and if the
condition is true then it will execute the statements and then after it increments or decrements the
value of a variable. But in the Will Condition is false then it will never Executes the Statement

Syntax:

while(condition)
{

//codetobeexecuted
}

flowchartofjavawhileloop Example:

publicclassWhileExample
{

publicstaticvoidmain(String[]args)
{

int i=1;
while(i<=10)
{

System.out.println(i);
i++;
}

}
Output:

1
2
3
4
5
6
7
8
9
10

dowhile

This is Also Called as Exit Controlled Loop we know that in The while loop the condition is
checkbefore the execution ofthe program butifthe condition isnottrue then itwillnotexecute the
statements so for this purpose we use the do while loop in this first it executes the statements and
then it increments the value of a variable and then last it checks the condition So in this either the
condition is true or not it Execute the statement at least one time.

Syntax:

Do
{

//codetobeexecuted
}while(condition);

flowchartofdowhileloop in java
Example:

publicclassDoWhileExample
{

publicstaticvoidmain(String[]args)
{

inti=1;
do
{

System.out.println(i);
i++;
}while(i<=10);
}}

Output:

1
2
3
4
5
6
7-
8
9
10

DIFFERENCEBETWEENWHILEANDDOWHILE LOOP [2Marks]

While loop Dowhileloop


Itisaloopingconstructthatwillexecuteonlyif the Itisaloopingconstructthatwillexecute atleast
test condition is true once if the test condition is false
Itisentrycontrolledloop Itisexitcontrolledloop
Itisgenerallyusedforimplementingcommon Ittypicallyusedforimplementingmenubased
looping situations programs where menu is required to be
printedatleastonce
Sysntax Syntax
While(condtion) Do
{ {
} }while(condition);

For Loop

InThisloopallthebasicoperationslikeinitialization,conditioncheckingandincrementingor
decrementing all these are performed in only one line. this is similar to the while loop for
performing its execution but only different in its syntax.
Syntax:

for(initialization;condition;expression)
{

//codetobeexecuted
}

Flowchart

Exampleclass
ForLoop

publicstaticvoidmain(Stringargs[])
{

int i;

for(i=1; i<=10; i++)


{

System.out.print(““+i);
}

Output :12345678910

You might also like