Unit 1
Unit 1
Introduction to java
It is used for:
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
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.
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.
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.
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.
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.
Stringargs[]–
hereStringargs[]declaresaparameternamedargswhichcontainsanarrayofobject of the
class type String.
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
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
5. Class Definition
A java program may contain multiple class definitions. Classes are primary and essential
elements of java program.
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.
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.
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.
1. temporary
2. permanent
1) To set the temporary path of JDK, you need to follow following steps:
For Example
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
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
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.
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.
Output
System.out.println("Age: "+a);
System.out.println("Temperature: "+t);
}
}
Output
Age: 25
Temperature: -10
Output
Output
Population: 2000000
Distance: 150000000
Output
publicclassGeeks {
publicstaticvoidmain(String[] args) {
floatpi=3.14f;
floatgravity=9.81f;
Output
Output
System.out.println("Grade: "+g);
System.out.println("Symbol: "+s);
}
}
Output
Grade: A
Symbol: $
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;
Output
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"};
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
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
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:
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:
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.
1 ++(Increment)
Increasesthevalueofoperandby1
Example:B++gives21
2 --(Decrement )
Decreasesthevalueofoperandby1
Example:B--gives 19
The Assignment Operators:
Therearefollowing assignmentoperatorssupportedbyJavalanguage:
Show Examples
SR.NO Operatorand Description
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
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 {}
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 {
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
if-else-if Multiple conditions if (marks >= 90) {...} else if (marks >= 80) {...}
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)
Inside If block
10 is less than 15
I am Not in if
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
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
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
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:
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;
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.
Create a Class
Main.java
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
int x = 5;
System.out.println(myObj.x);
}
Java Class Methods
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
System.out.println("Hello World!");
myMethod();
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
// Static method
// Public method
// Main method
Method in Java
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
// code to be executed
Example Explained
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
myMethod();
}
// Outputs "I just got executed!"
Example
myMethod();
myMethod();
myMethod();
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:
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
Example
myMethod("Jenny", 8);
myMethod("Anja", 31);
// Liam is 5
// Jenny is 8
// Anja is 31
Java Constructors
Create a constructor:
public Main() {
Main myObj = new Main(); // Create an object of class Main (This will call the constructor)
// Outputs 5
Constructor Parameters
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
int x;
public Main(int y) {
x = y;
System.out.println(myObj.x);
Types of Constructor
No-Arg Constructor
Parameterized Constructor
Default Constructor
If a constructor does not accept any parameters, it is known as a no-argument constructor. For
example,
private Constructor() {
class Main {
int i;
private Main() {
i = 5;
System.out.println("Constructor is called");
Output:
Constructor is called
Value of i: 5
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 {
Output
String languages;
Main(String lang) {
languages = lang;
Output
C Programming Language
Based on the argument passed, the language variable is initialized inside the constructor.
If we do not create any constructor, the Java compiler automatically creates a no-arg constructor
during the execution of the program.
int a;
boolean b;
System.out.println("Default Value:");
Output
Default Value:
a=0
b = false
Access Modifiers
class College {
There are four access modifiers keywords in Java and they are:
If we do not explicitly specify any access modifier for classes, methods, variables, etc, then by
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
When variables and methods are declared private, they cannot be accessed outside of the class.
For example,
class Data {
// private variable
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:
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 {
// getter method
return this.name;
// setter method
this.name= name;
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.
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
System.out.println("I am in college");
stud.display();
Output:
I am in college
In the above example, we have a protected method named display() inside the College class.
We then created an object stud of the Student class. Using the object we tried to access the
Since protected methods can be accessed from the child classes, we are able to access the method
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 variable
// public method
System.out.println("I am inCollege.");
// Main.java
public class Main {
c.Count = 40;
c.display();
Output:
I am inCollege.
we have 40student.
Here,
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
// method body
counter++;
incrementCounter();
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
Syntax
final dataType variableName = value;
// method body
// class body
Ex:
obj.display();
String Manipulation
UpperCase/LowerCase: Converts all characters in the string to upper case or lower case.
2. String Comparison
3. String Conversion
Java Arrays
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.
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;
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
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,
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
// initialize array
age[0] = 12;
age[1] = 4;
age[2] = 5;
..
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.
We can access the element of an array using the index number. Here is the syntax for accessing
elements of an array,
array[index]
// create an array
Output
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.
In Java, we can also loop through each element of the array. For example,
Example: Using For Loop
class Main {
// create an array
System.out.println(age[i]);
Output
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,
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
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
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;
System.out.print(““+i);
}
Output :12345678910