JAVA Unit 2
JAVA Unit 2
04/16/2024
SYLLABUS
04/16/2024
CONTROL STATEMENTS
04/16/2024
CONTROL STATEMENTS
Control statement
Selection
Iteration
Jump
04/16/2024
Java's program control statements
A programming language uses control statements to cause the flow of execution to advance and
branch based on changes to the state of a program.
Java's program control statements can be put into the following categories:
selection,
iteration,
jump.
Selection statements allow your program to choose different paths of execution based upon the
outcome of an expression or the state of a variable.
Iteration statements enable program execution to repeat one or more statements (that is, iteration
statements form loops).
04/16/2024
Jump statements allow your program to execute in a nonlinear fashion.
SELECTION STSTEMENT
Selection statements allow you to control the flow of program execution, on the basis of the outcome
of an expression or state of a variable, known during runtime
These statements decides the flow of the execution based on some conditions.
04/16/2024
SELECTION STSTEMENT
If statement
Selection
Simple if
If statement
If else
Switch
statement
If else if
Nested if
04/16/2024
IF STATEMENT
It is used to take decision based on a single condition. Flow Chart:
Syntax:
Statement
04/16/2024
IF STATEMENT
04/16/2024
IF STATEMENT
import java.in;
public class Ifram
{
public static void main(String[] args)
{ int age;
Scanner inputDevice = new Scanner(System.in);
System.out.print("Please enter Age: ");
age = inputDevice.nextInt();
if (age > 18)
System.out.println("above 18 ");
}
}
04/16/2024
IF ELSE STATEMENT
Syntax:
Flow Chart:
if(condition)
{
Statements; True False
}
else
{
Statements;
}
04/16/2024
IF ELSE STATEMENT
The if else statement has one condition and two statement blocks - True block and False
block
If condition is True; control will execute the statement in the true block
If condition is False; control will execute the statement in false block
04/16/2024
IF ELSE STATEMENT
Flow Chart:
If within If within
else else
04/16/2024
NESTED IF STATEMENT
04/16/2024
NESTED IF STATEMENT
04/16/2024
IF-ELSE-IF LADDER STATEMENT
Tr False
ue
If
within
else
04/16/2024
IF-ELSE-IF LADDER STATEMENT
// Demonstrate if-else-if statements. season = "Summer";
class ram{ else if(month == 9 || month == 10 || month == 11)
public static void main(String args[]) { season = "Autumn";
else
int month = 5; // May season = "Bogus Month";
String season; System.out.println(“May is in the " + season + ".");
if(month == 12 || month == 1 || month == 2) }}
season = "Winter";
else if(month == 3 || month == 4 || month == 5)
season = "Spring"; output :
May is in the Spring.
else if(month == 6 || month == 7 || month == 8)
04/16/2024
IF-ELSE-IF LADDER STATEMENT
public class IfElseIfram else if(marks>=70 && marks<80)
{ {
public static void main(String[] args) System.out.println("B grade");
{ }
int marks=75; else if(marks>=80 && marks<90)
if(marks<50) {
{ System.out.println("A grade");
System.out.println("fail"); } Output
} else if(marks>=90 && marks<100) B grad
else if(marks>=50 && marks<60) {
{ System.out.println("A+ grade");
System.out.println("D grade"); }
} Else
else if(marks>=60 && marks<70) {
{ System.out.println("Invalid!");
System.out.println("C grade"); }
} }
}
04/16/2024
SWITCH STATEMENT
Switch statement is used when you have multiple possibilities for the if statement.
Switch(variable/expression)
The basic format of the switch statement is:
Syntax: {
Case value1:
switch(variable /expression)
//execute your code
{
Statements;
case 1: Break;
Case statements; Case value1:
//execute your code break; //execute your code
Statements;
case n: //execute your code break;
Break;
default: default: //execute your code
//execute your code break; }
}
04/16/2024
SWITCH STATEMENT
Switch statement with break statement Switch statement without break statement
Start Start
Case A Statements
Case A Case A Case A Statements
True
break;
Tru
False e
Case B Statements False
Case B break; Case B Case B Statements
True Tru
False e
Case C Statements False
… break; … Case C Statements
True
True
False
False
End
End
04/16/2024
SWITCH STATEMENT
The variable or expression should be of type int, short, char
Each of the values specified in the case statements must be of a type compatible with the expression.
Each case value should be a unique
Duplicate case values are not allowed.
switch statement working principle:
The value of the expression or variable is compared with each of the values in the case statements.
If expression or variable is found, the code sequence following that case statement is executed.
If no expression or variable there, then the default statement is executed.
The break statement is used inside the switch to terminate a statement sequence.
When a break statement is encountered, execution branches to the first line of code that follows the
entire switch statement.
04/16/2024
SWITCH STATEMENT
04/16/2024
SWITCH STATEMENT
04/16/2024
NESTED SWITCH STATEMENTS
A switch statement within a switch statement is called Nested switch Statement
public class Example{
public static void main(String args[])
{
int out = 1;
int in = 1;
switch(out)
{
case 1:
switch(in) //Nested switch
{ Output
case 1: Inner case
System.out.println(“Inner case");
break;
}
}}}
04/16/2024
FEATURES OF THE SWITCH CASE
The switch differs from the if in that switch can only test for equality, whereas if can evaluate any
type of Boolean values(0’s and 1’s ), the switch looks only for a match between the value of the
expression and one of its case values.
04/16/2024
ITERATION STATEMENTS
These iteration statements create what we commonly call loops. The loop repeatedly executes the
same set of instructions until a condition is reached.
For
loop
Parts of looping statements:
While Initialization
Condition checking
Do Increment and decrement
While Execution
04/16/2024
ITERATION STATEMENTS
Iteration statements can be categorized based on based on where the condition is checking
Loop
04/16/2024
For loop
Initialization
Syntax : F
cond
for(initialization; condition; iteration)
{ T
False Statements
// body
True
}
Statements
Initialization: It is the initial condition which is executed once when the loop starts.
Condition: It is the second condition which is executed each time to test the condition of the loop. It
continues execution until the condition is false. It is an optional condition.
Statement: The statement of the loop is executed each time until the second condition is false.
Increment/Decrement:
04/16/2024 It increments or decrements the variable value. It is an optional condition.
For loop
In if body no more than one statement is being repeated, no need for the curly braces
04/16/2024
For loop execution
ti o n
cu
Ex e
04/16/2024
For loop execution
Initialization Output
Statement
for( x=0;x<=5;x++)
{
System.out.println(x);
} 0
Variable x value
in memory
04/16/2024
For loop execution
See the out
put
See x value
Condition is Output
true 0
for( x=0;x<=5;x++)
{
System.out.println(x); 0
} Variable x value
in memory
04/16/2024
For loop execution
See the out
put
See the x
value
Output
Increment 0
for( x=0;x<=5;x++)
{
System.out.println(x); 1
} Variable x value
in memory
04/16/2024
For loop execution
See the out
put
See the x
Condition value
Output
checking 0
1
for( x=0;x<=5;x++)
{
System.out.println(x); 1
} Variable x value
in memory
04/16/2024
For loop execution
See the out
put
See the x
Increment x value
Output
value
0
1
for( x=0;x<=5;x++)
{
System.out.println(x); 2
} Variable x value
in memory
04/16/2024
For loop execution
See the out
put
See the x
Condition value
Output
checking 0
1
2
for( x=0;x<=5;x++)
{
System.out.println(x); 2
} Variable x value
in memory
04/16/2024
For loop execution
See the out
put
See the x
Increment value
Output
the x value 0
1
2
for( x=0;x<=5;x++)
{
System.out.println(x); 3
} Variable x value
in memory
04/16/2024
For loop execution
See the out
put
See the x
Condition value
checking Output
0
1
2
for( x=0;x<=5;x++) 3
{
System.out.println(x); 3
} Variable x value
in memory
04/16/2024
For loop execution
See the out
put
See the x
value
increment the Output
x value 0
1
2
3
for( x=0;x<=5;x++)
{ 4
System.out.println(x); Variable x value
} in memory
04/16/2024
For loop execution
See the out
put
See the x
Condition value
Output
checking 0
1
2
for( x=0;x<=5;x++) 3
{ 4
System.out.println(x); 4
} Variable x value
in memory
04/16/2024
For loop execution
See the out
put
See the x
increment value
Output
the x value 0
1
2
for( x=0;x<=5;x++) 3
{ 4
System.out.println(x); 5
} Variable x value
in memory
04/16/2024
For loop execution
See the out
put
04/16/2024
For loop execution
See the out
put
See the x
Increment
value
the x value Output
0
1
2
for( x=0;x<=5;x++) 3
{ 4
5
System.out.println(x); 6
} Variable x value
in memory
04/16/2024
For loop execution
See the out
put
04/16/2024
Using the Comma
There will be times when you will want to include more than one statement in the initialization and
iteration portions of the for loop.
class forvar
boolean no= false; {
for(int i=1; !no; i++) public static void main(String args[]) {
int x;
{ boolean no = false;
i = 0;
// ...
for( ; !no; ) {
if(interrupted()) System.out.println("i is " + x);
if(x == 10) x = true;
no = true; x++;
}
}
}}
04/16/2024
For-Each Loop
There is also a "for-each" loop, which is used exclusively to loop through elements in an array:
}
04/16/2024
While loop in Java
FLOESHORT
start
// while loop
//Initialization statement
false condi FALSE
while (condition_st)
tion
{ True TRUE
body; statement
//increment/decrement
} Statement
// next statement
The condition can be any valid expression
04/16/2024
While loop in Java - Example
import java.io. * ;
public class WhileLoop
{
public static void main(String[] args) Output
{ Learning Java
int x= 0; The value of x is = 0
System.out.println("Learning Java "); The value of x is = 1
while (x < 5) The value of x is = 2
{ The value of x is = 3
System.out.println("The value of i is = " + x); The value of x is = 4
x++; Loop broke out of the loop
}
System.out.println(“Loop broke out of the
loop");
}
}
04/16/2024
While loop execution
Initialization
Statement
x= 0;
Condition
while (x < 5) statement
{
Execution
System.out.println("Learning Java Mvj College");statement
Increment
statement
System.out.println("The value of i is = " + x);
x++;
}
04/16/2024
While loop execution
See the x
x= 0; Condition value
checking (0<5)
while (x < 5) Output
Learning Java Mvj College
{ The value of x is = 0
System.out.println("The value of i is = " +
X = 1 value
incremented 0
x); Variable x value
in memory
x++;
}
04/16/2024
While loop execution
See the x
x= 0; Condition value
checking(0<1)
while (x < 5) Output
Learning Java Mvj College
{ The value of x is = 0
System.out.println("The value of i is = " + The value of x is =1
X=2 value
incremented 1
x); Variable x value
in memory
x++;
}
04/16/2024
While loop execution
See the x
x= 0; Condition value
checking (2<5)
while (x < 5) Output
Learning Java Mvj College
{ The value of x is = 0
System.out.println("The value of i is = " + The value of x is =1
X =3 value
The value of x is =2 2
incremented
x); Variable x value
in memory
x++;
}
04/16/2024
While loop execution
See the x
x= 0; Condition value
checking (3<5)
while (x < 5) Output
Learning Java Mvj College
{ The value of x is = 0
System.out.println("The value of i is = " + The value of x is =1
X =4 value
The value of x is =2 3
incremented
x); The value of x is =3 Variable x value
in memory
x++;
}
04/16/2024
While loop execution
04/16/2024
While loop execution
See the
Final Out put
Condition See the x
x= 0; checking (5<5) value
false
while (x < 5) Output
Learning Java Mvj College
{ The value of x is = 0
System.out.println("The value of i is = " + The value of x is =1
The value of x is =2 5
x); The value of x is =3 Variable x value
The value of x is =4 in memory
x++;
}
Loop will be terminate
04/16/2024
DO-WHILE
The do-while loop executes its body at least once, because its conditional expression is at the last of
the loop.
The difference between a while and a do-while loop, is that do-while evaluates its expression at the
last of the loop, instead of the top. The do-while loop executes at least one time, it will check the
expression before to the next iteration.
Repeat statements 1 or more times until some truth value is false.
Syntax: initialization r=1
do do
{ {
statements; System.out.println(r);
increment/decrement; r+=1;//r=r+1
} }
while(condition/expression); while(r==20);
04/16/2024
DO-WHILE Initialization
statement
Flow chart :
public class dowhile
{
do public static void main(String args[])
Statements { Output
int r = 0; Increment
statement 0
do 1
{ 2
Condit System.out.print("value of x : " + r ); 3
ion r++; 4
TRUE
System.out.print("\n");
FALSE }while( r < 5 ); Condition
} statement
}
04/16/2024
DO-WHILE
04/16/2024
DO-WHILE- EXAMPLE
Public class dowhile { case ‘2':
public static void main(String args[]) System.out.println("The do-while:\\n");
throws java.io.IOException { System.out.println("do {");
char op;
System.out.println(" statement;");
do {
System.out.println(“Three Loop:"); System.out.println("} while (condition);");
System.out.println(" 1. while"); break;
System.out.println(" 2. do-while"); case ‘3':
System.out.println(" 3. for\\n"); System.out.println("The for:\\n");
System.out.println(“Select one:"); System.out.print("for(init; condition; iteration)");
op = (char) System.in.read(); System.out.println(" statement;");
} while( op < '1' || op > '5'); break;
System.out.println("\\n"); }
switch(choice) {
}}
case ‘1':
System.out.println("The while:\\n");
System.out.println("while(condition)
statement;"); break;
04/16/2024
DO-WHILE- EXAMPLE
Output
Three
1. while
2. do-while
3. for
Select one:
2
The do-while:
do {
statement;
} while (condition);
04/16/2024
Nested Loops
The one loop may be inside another loop is called as nested loop. Nested dowhile loop
Nested For loop – syntax : Nested while loop – syntax : – syntax :
do
for ( initialization; condition; increment ) while (condition)
{
{ { do
for ( initialization; condition; increment ) while (condition) {
// while inner loop
{ { statements
// inner loop statements // while inner loop statements }while (condition);
// while outer loop
} } statements
// outer loop statements // while outer loop statements } while (condition);
} }
04/16/2024
Nested Loops
Public class NestedForDemo
{
public static void main(String args[] )
{
int x,y; Output
for(x=1;x<=5;x++) 1
{ 22
for(y=1;y<=y;j++) 333
{ 4444
System.out.print(y); 55555
}
System.out.println(“\n”);
}
}
}
04/16/2024
Jump Statements
The jump statements transfer control the program one part to another part.
Java supports three jump statements:
Jump
Break
Continue
Return
04/16/2024
Break statement
The break statement stop the currently executing loop cycle and resumes at the first statement
following the current loop statement.
04/16/2024
Break statement - Example
// Exit a loop.
Public class BLoop {
public static void main(String args[])
{ Output
r: 0
for(int r=0; r<10; i++) {
r: 1
if(r == 5) break; // terminate loop if r is 5 r: 2
System.out.println(“r: " + r); r: 3
r: 4
} Exit the loop
System.out.println(“Exit the loop.");
}
}
04/16/2024
Break statement - Example
Public class breaktype1
{
public static void main(String args[])
{
int r= 0;
while (r<=10)
{ Output :
System.out.println("\n" + r); 0
r++; 1
if (r==5) 2
{ 3
break; 4
}
}
}
}
04/16/2024
Break statement - Example
Public class Break1
{
public static void main(String[] args)
{
for(int r=0; r<10; r++) Output
{ 0
if(r==5) 1
{ 2
break; 3
} 4
System.out.println(r); Outer for loop
}
System.out.println(“Outer for loop");
}
}
04/16/2024
USING BREAK AS A FORM OF GOTO
// Using break as a form of goto.
class Breakgoto {
public static void main(String args[]) {
boolean r = true;
one:
{
two: Output
{ Before the break.
three:
{ This is after second block.
System.out.println("Before the break.");
if(t) break second; // break out of second block
System.out.println("This won't execute");
}
System.out.println("This won't execute");
}
System.out.println("This is after two block.");
}
04/16/2024
CONTINUE STATEMENT
This statement is used only within looping statements.
When the continue statement is encountered, the next iteration starts.
The remaining statements in the loop are skipped. The execution starts from the top of loop again.
That is, it causes program control to transfer back to the caller of the method.
Example Program.
04/16/2024
Java - Methods
A Java method is a collection of statements that are grouped together to perform an
operation.
When you call the System.out.println() method, for example, the system actually executes
several statements in order to display a message on the console.
• myMethod() is the name of the
public class Main { method
• static means that the method belongs
static void myMethod() {
to the Main class and not an object of
// code to be executed the Main class.
• void means that this method does not
}} have a return value.
04/16/2024
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:
If you want the method to return a value, you can use a primitive data type (such as int,
char, etc.) instead of void, and use the return keyword inside the method:
public class Main { public class Main {
static int myMethod(int x) { static int myMethod(int x, int y) {
return 5 + x; return x + y;
} }
public static void main(String[]
args) public static void main(String[] args) {
{ System.out.println(myMethod(3)); System.out.println(myMethod(5, 3));
} }
} }
04/16/2024
A Method with If...Else
• It is common to use if...else statements inside methods:
public class Main {
// Create a checkAge() method with an integer variable called age
static void checkAge(int age) {
04/16/2024
Method Overloading
With method overloading, multiple methods can have the same name with
different parameters:
int myMethod(int x) static int plusMethodInt(int x, int y)
{
float myMethod(float x)
return x + y;
double myMethod(double x, double y) }
04/16/2024
Instead of defining two methods that should do the same thing, it is better to
overload one.
In the example below, we overload the plusMethod method to work for both int
and double:
static int plusMethod(int x, int y)
{
return x + y;
}
static double plusMethod(double x, double y) {
return x + y;
}
public static void main(String[] args) {
int myNum1 = plusMethod(8, 5);
double myNum2 = plusMethod(4.3, 6.26);
System.out.println("int: " + myNum1);
System.out.println("double: " + myNum2);
}
04/16/2024
Java Math
The Java Math class has many methods that allows you to perform
mathematical tasks on numbers.
Math.max(x,y)
Math.max(5, 10);
Math.min(x,y)
Math.min(5, 10);
Math.sqrt(x)
Math.sqrt(64);
Math.abs(x)
Math.abs(-4.7);
Random Numbers
Math.random(); int randomNum = (int)(Math.random() * 101);
04/16/2024
Java Arrays
Arrays are used to store multiple values in a single variable, instead of declaring
separate variables for each value.
To declare an array, define the variable type with square brackets:
String[] cars;
04/16/2024
Access the Elements of an Array
You access an array element by referring to the index number.
This statement accesses the value of the first element in cars:
04/16/2024
Loop Through an Array with For-Each
There is also a "for-each" loop, which is used exclusively to loop through
elements in arrays:
Syntax
for (type variable :
arrayname) {
...
}
Example
String[] cars = {"Volvo", "BMW", "Ford",
"Mazda"};
for (String i : cars)
{
System.out.println(i);
}
04/16/2024
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:
04/16/2024
Create an Object
In Java, an object is created from a class. We have already created the class named
MyClass, so now we can use this to create objects.
To create an object of MyClass, 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:
04/16/2024
Multiple Objects
You can create multiple objects of one class:
Example
Create two objects of Main:
04/16/2024
Using Multiple Classes
You can also create an object of a class and access it in another class. This is often
used for better organization of classes (one class has all the attributes and
methods, while the other class holds the main() method (code to be executed)).
Remember that the name of the java file should match the class name. In this
example, we have created two files in the same directory/folder:
• Main.java
• Second.java
Main.java Second.java
public class Main { class Second {
int x = 5; public static void main(String[] args) {
}
Main myObj = new Main();
System.out.println(myObj.x);
}
}
04/16/2024
Java Class Attributes
we used the term "variable" for x in the example (as shown below). It is actually
an attribute of the class. Or you could say that class attributes are variables within
a class:
Example
Create a class called "Main" with two attributes: x
and y:
04/16/2024
Accessing Attributes
You can access attributes by creating an object of the class, and by using the dot
syntax (.):
The following example will create an object of the Main class, with the name
myObj. We use the x attribute on the object to print its value:
Example
Create an object called "myObj" and print the value of x:
04/16/2024
• If you don't want the ability to override existing values, declare the attribute as final:
The final keyword is useful when you want a variable to always store the same value, like P
The final keyword is called a "modifier".
04/16/2024
Multiple Objects
• If you create multiple objects of one class, you can change the attribute values in
one object, without affecting the attribute values in the other:
Example
Change the value of x to 25 in myObj2, and leave x in myObj1 unchanged:
04/16/2024
Multiple Attributes
You can specify as many attributes as you want:
Example
public class Main {
String fname = "John";
String lname = "Doe";
int age = 24;
04/16/2024
Java Class Methods
Methods are declared within a class, and that they are used to perform certain
actions:
Example
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;
04/16/2024
Example
Inside main, call myMethod():
04/16/2024
Static vs. Non-Static
• You will often see Java programs that have either static or public attributes and
methods.
• 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:
// Public method
Example public void myPublicMethod() {
An example to demonstrate the differences System.out.println("Public methods must be called by
between static and public methods: creating objects");
}
public class Main {
// Main method
// Static method public static void main(String[] args) {
static void myStaticMethod() { myStaticMethod(); // Call the static method
System.out.println("Static methods can be // myPublicMethod(); This would compile an error
called without creating objects");
} Main myObj = new Main(); // Create an object of Main
myObj.myPublicMethod(); }}
04/16/2024
Access Methods With an Object
Example
Create a Car object named myCar. Call the fullThrottle() and speed() methods on the myCar object, and run the
program:
// Create a Main class
public class Main {
// Create a fullThrottle() method
public void fullThrottle() {
System.out.println("The car is going as fast as it can!");
}
// Create a speed() method and add a parameter
public void speed(int maxSpeed) {
System.out.println("Max speed is: " + maxSpeed);
}
// Inside main, call the methods on the myCar object
public static void main(String[] args) {
Main myCar = new Main(); // Create a myCar object
myCar.fullThrottle(); // Call the fullThrottle() method
myCar.speed(200); // Call the speed() method
}
}
04/16/2024
Example explained
We created a custom Main class with the class keyword.
2) We created the fullThrottle() and speed() methods in the Main class.
3) The fullThrottle() method and the speed() method will print out some text, when they
are called.
4) The speed() method accepts an int parameter called maxSpeed - we will use this in
8).
5) In order to use the Main class and its methods, we need to create an object of the
Main Class.
6) Then, go to the main() method, which you know by now is a built-in Java method
that runs your program (any code inside main is executed).
7) By using the new keyword we created an object with the name myCar.
8) Then, we call the fullThrottle() and speed() methods on the myCar object, and run
the program using the name of the object (myCar), followed by a dot (.), followed by
the name of the method (fullThrottle(); and speed(200);). Notice that we add an int
parameter of 200 inside the speed() method.
04/16/2024
Using Multiple Classes
It is a good practice to create an object of a class and access it in another class.
Remember that the name of the java file should match the class name. In this
example, we have created two files in the same directory:
Main.java
Second.java
Main.java Second.java
public class Main { class Second {
public void fullThrottle() { public static void main(String[] args) {
System.out.println("The car is going as fast as it can!");
Main myCar = new Main();
}
myCar.fullThrottle();
public void speed(int maxSpeed) { myCar.speed(200);
System.out.println("Max speed is: " + maxSpeed); }
} }
}
04/16/2024
Constructors in Java
In Java, a constructor is a block of codes similar to the method. It is called when
an instance of the class is created. At the time of calling constructor, memory for
the object is allocated in the memory.
It is a special type of method which is used to initialize the object.
Every time an object is created using the new() keyword, at least one constructor
is called.
It calls a default constructor if there is no constructor available in the class. In
such case, Java compiler provides a default constructor by default.
There are two types of constructors in Java: no-arg constructor, and parameterized
constructor.
Note: It is called constructor because it constructs the values at the time of object
creation. It is not necessary to write a constructor for a class. It is because java
compiler creates a default constructor if your class doesn't have any.
04/16/2024
Rules for creating Java constructor
There are two rules defined for the constructor.
Constructor name must be the same as its class name
A Constructor must have no explicit return type
A Java constructor cannot be abstract, static, final, and synchronized
04/16/2024
Java Default Constructor
A constructor is called "Default Constructor" when it doesn't have any parameter.
Syntax of default constructor:
<class_name>(){}
04/16/2024
Java Parameterized Constructor
A constructor which has a specific number of parameters is called a parameterized
constructor.
The parameterized constructor is used to provide different values to distinct
objects. However, you can provide the same values also.
//Java Program to demonstrate the use //method to display the values Student4 s2 = new
of the parameterized constructor. void display() Student4(222,"Aryan");
class Student4{ {System.out.println(id+" //calling method to
int id; "+name);} display the values of object
String name; s1.display();
//creating a parameterized public static void main(String s2.display();
constructor args[]){ }
Student4(int i,String n){ //creating objects and passing }
id = i; values
name = n; Student4 s1 = new
} Student4(111,"Karan");
04/16/2024
Constructor Overloading in Java
In Java, a constructor is just like a method but without return type. It can also be
overloaded like Java methods.
Constructor overloading in Java is a technique of having more than one
constructor with different parameter lists. They are arranged in a way that each
constructor performs a different task. They are differentiated by the compiler by
the number of parameters in the list and their types.
//Java program to overload id = i; void display()
constructors name = n; {System.out.println(id+"
class Student5{ } "+name+" "+age);}
int id; //creating three arg public static void main(String
String name; constructor args[]){
int age; Student5(int i,String n,int a){ Student5 s1 = new
//creating two arg constructor id = i; Student5(111,"Karan");
Student5(int i,String n){ name = n; Student5 s2 = new
age=a; Student5(222,"Aryan",25);
} s1.display();
s2.display(); } }
04/16/2024
04/16/2024
Java Copy Constructor
There is no copy constructor in Java. However, we can copy the values from one
object to another like copy constructor in C++.
There are many ways to copy the values of one object into another in Java. They
are:
By constructor
By assigning the values of one object into another
By clone() method of Object class
04/16/2024
class Student6{
int id;
String name;
//constructor to initialize integer and string
Student6(int i,String n){
id = i;
name = n;
}
//constructor to initialize another object
Student6(Student6 s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}
04/16/2024
Copying values without constructor
We can copy the values of one object into another by assigning the objects values
to another object. In this case, there is no need to create the constructor.
class Student7{
int id;
String name;
Student7(int i,String n){
id = i;
name = n;
}
Student7(){}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student7 s1 = new Student7(111,"Karan");
Student7 s2 = new Student7();
s2.id=s1.id;
s2.name=s1.name;
s1.display();
s2.display();
} }
04/16/2024
Destructor in Java
• It is a special method that automatically gets called when an object is no longer
used.
• When an object completes its life-cycle the garbage collector deletes that object
and deallocates or releases the memory occupied by the object.
Advantages of Destructor
• It releases the resources occupied by the object.
• No explicit call is required, it is automatically invoked at the end of the program
execution.
• It does not accept any parameter and cannot be overloaded.
04/16/2024
How does destructor work?
• When the object is created it occupies the space in the heap.
• These objects are used by the threads.
• If the objects are no longer is used by the thread it becomes eligible for the
garbage collection.
• The memory occupied by that object is now available for new objects that are
being created.
• It is noted that when the garbage collector destroys the object, the JRE calls the
finalize() method to close the connections such as database and network
connection.
• The destructor notifies exactly when the object will be destroyed. While in Java
the garbage collector does the same work automatically.
• These two approaches to memory management have positive and negative effects.
04/16/2024
Java finalize() Method
• It is difficult for the programmer to forcefully execute the garbage collector to
destroy the object.
• Java provides an alternative way to do the same.
• The Java Object class provides the finalize() method that works the same as the
destructor. public class DestructorExample
{
protected void finalize throws Throwable() public static void main(String[] args)
{ {
//resources to be close DestructorExample de = new DestructorExample ();
} de.finalize();
de = null;
System.gc();
System.out.println("Inside the main() method");
}
protected void finalize()
{
System.out.println("Object is destroyed by the Garbage Collector");
04/16/2024
Java static keyword
• The static keyword in Java is used for memory management mainly.
• We can apply static keyword with variables, methods, blocks and nested classes.
• The static keyword belongs to the class than an instance of the class.
Java static variable
•If you declare any variable as static, it is known as a static variable.
•The static variable can be used to refer to the common property of all objects
(which is not unique for each object), for example, the company name of
employees, college name of students, etc.
•The static variable gets memory only once in the class area at the time of class
loading.
Advantages of static variable
•It makes your program memory efficient (i.e., it saves memory).
04/16/2024
Example of static variable
class Student{ //Test class to show the values of objects
int rollno;//instance variable public class TestStaticVariable1{
String name; public static void main(String args[]){
static String college ="ITS";//static variable Student s1 = new Student(111,"Karan");
//constructor Student s2 = new Student(222,"Aryan");
Student(int r, String n){
//we can change the college of all objects
rollno = r;
name = n;
by the single line of code
} //Student.college="BBDIT";
//method to display the values s1.display();
void display (){System.out.println(rollno+" s2.display();
"+name+" "+college);} }
} }
04/16/2024
Program of the counter without static variable
• In this example, we have created an instance variable named count which is
incremented in the constructor.
• Since instance variable gets the memory at the time of object creation, each object
will have the copy of the instance variable.
• If it is incremented, it won't reflect other objects. So each object will have the
value 1 in the count variable.
class Counter{ public static void main(String args[]){
int count=0;//will get memory //Creating objects
each time when the instance is Counter c1=new Counter();
created Counter c2=new Counter();
Counter c3=new Counter();
Counter(){ }
count++;//incrementing value }
System.out.println(count);
}
04/16/2024
Program of counter by static variable
• As we have mentioned above, static variable will get the memory only once, if
any object changes the value of the static variable, it will retain its value.
class Counter2{
static int count=0;//will get memory only
once and retain its value
Counter2(){
count++;//incrementing the value of static
variable
System.out.println(count);
}
class A{
int a=40;//non static
04/16/2024
Java static block
• Is used to initialize the static data member.
• It is executed before the main method at the time of classloading.
class A2{
static
{
System.out.println("static block is invoked");
}
public static void main(String args[]){
System.out.println("Hello main");
}
}
04/16/2024
• Can we execute a program without main() method?
• No, one of the ways was the static block, but it was possible till JDK 1.6.
Since JDK 1.7, it is not possible to execute a Java class without the main
method.
class A3{
static{
System.out.println("static block is invoked");
System.exit(0);
}
}
04/16/2024
Super keyword in java
• Super is a keyword of Java which refers to the immediate parent of a class and is
used inside the subclass method definition for calling a method defined in the
superclass.
• A superclass having methods as private cannot be called.
• Only the methods which are public and protected can be called by the keyword
super. It is also used by class constructors to invoke constructors of its parent class.
super.<method-name>();
• Instance refers an instance variable of the current class by default, but when you have to refer parent class
instance variable, you have to use super keyword to distinguish between parent class (here employee) instance
variable and current class (here, clerk) instance variable.
04/16/2024
Final Keyword in Java
• Final is a keyword in Java that is used to restrict the user and can be
used in many respects. Final can be used with:
• Class
• Methods
• Variables
Class Declared as Final
final class stud {
// Methods cannot be extended to its sub class
}
class books extends stud {
void show() {
System.out.println("Book-Class method");
}
public static void main(String args[]) {
books B1 = new books();
B1.show();
}
}
04/16/2024
Method declared as Final
• A method declared as final cannot be overridden; this means even when a child
class can call the final method of parent class without any issues, but the
overriding will not be possible.
• Here is a sample program showing what is not valid within a Java program when a
method is declared as final.
class stud {
final void show() {
System.out.println("Class - stud : method defined");
}
}
class books extends stud {
void show() {
System.out.println("Class - books : method defined");
}
public static void main(String args[]) {
books B2 = new books();
B2.show();
04/16/2024}}
Variable declared as final
• Once a variable is assigned with the keyword final, it always contains the same
exact value.
• Again things may happen like this; if a final variable holds a reference to an object
then the state of the object can be altered if programmers perform certain
operations on those objects, but the variable will always refer to the same object.
• . A final variable that is not initialized at the time of declaration is known as a
blank final variable.
• If you are declaring a final variable in a constructor, then you must initialize the
blank final variable within the constructor of the class. Otherwise, the program
might show a compilation error.
04/16/2024
import java.util.*;
import java.lang.*;
import java.io.*;
class stud {
final int val;
stud() {
val = 60;
}
void method() {
System.out.println(val);
}
public static void main(String args[])
{
stud S1 = new stud();
S1.method();
}
}
04/16/2024
this keyword in java
• There can be a lot of usage of java this keyword.
• In java, this is a reference variable that refers to the current object.
Usage of java this keyword
Here is given the 6 usage of java this keyword.
• this can be used to refer current class instance variable.
• this can be used to invoke current class method (implicitly)
• this() can be used to invoke current class constructor.
• this can be passed as an argument in the method call.
• this can be passed as argument in the constructor call.
• this can be used to return the current class instance from the method.
04/16/2024
Problem without this keyword
In the above example, parameters (formal arguments) and instance variables are same. So,
we are using this keyword to distinguish local variable and instance variable.
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
rollno=rollno;
name=name;
fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis1{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
04/16/2024
Solution of the above problem by this keyword
class Student{ class Student{ //this Keyword not Required
int rollno; int rollno;
String name; String name;
float fee; float fee;
Student(int rollno,String name,float fee){ Student(int r,String n,float f){
this.rollno=rollno; rollno=r;
this.name=name; name=n;
this.fee=fee; fee=f;
} }
void display(){System.out.println(rollno+" void display(){System.out.println(rollno+" "+name+"
"+name+" "+fee);} "+fee);}
} }
class TestThis2{ class TestThis3{
public static void main(String args[]){ public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f); Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f); Student s2=new Student(112,"sumit",6000f);
s1.display(); s1.display();
s2.display(); s2.display();
}} }}
04/16/2024
this: to invoke current class method
• You may invoke the method of the current class by using the this keyword. If you
don't use the this keyword, compiler automatically adds this keyword while invoking
the method. Let's see the example
class A{ // Calling parameterized constructor from default
void m(){System.out.println("hello m");} constructor:
void n(){ class A{
System.out.println("hello n"); A(){
//m();//same as this.m() this(5);
this.m(); System.out.println("hello a");
} }
} A(int x){
class TestThis4{ System.out.println(x);
public static void main(String args[]){ }
A a=new A(); }
a.n(); class TestThis6{
}} public static void main(String args[]){
A a=new A();
04/16/2024 }}
Real usage of this() constructor call
• The this() constructor call should be used to reuse the constructor from the
constructor. It maintains the chain between the constructors i.e. it is used for
constructor chaining. Let's see the example given below that displays the actual use of
thisclass
keyword.
Student{ this(rollno,name,course);//reusing constructor
int rollno; this.fee=fee;
String name,course; }
float fee; void display(){System.out.println(rollno+"
Student(int rollno,String name,String "+name+" "+course+" "+fee);}
course){ }
this.rollno=rollno; class TestThis7{
this.name=name; public static void main(String args[]){
this.course=course; Student s1=new Student(111,"ankit","java");
} Student s2=new
Student(int rollno,String name,String Student(112,"sumit","java",6000f);
course,float fee){ s1.display();
s2.display();
}}
04/16/2024
//this: to pass as an argument in the method //this: to pass as argument in the
class S2{ constructor call
void m(S2 obj){ class B{
System.out.println("method is invoked"); A4 obj;
} B(A4 obj){
void p(){ this.obj=obj;
m(this); }
} void display(){
public static void main(String args[]){ System.out.println(obj.data);//using data member of
S2 s1 = new S2(); A4 class
s1.p(); } }
} class A4{
} int data=10;
A4(){
B b=new B(this);
b.display();
}
public static void main(String args[]){
A4 a=new A4();
} }
04/16/2024
//this keyword can be used to return current class //Example of this keyword that you
instance return as a statement from the method
return_type method_name(){ class A{
return this; A getA(){
} return this;
}
void msg(){System.out.println("Hello
//Proving this keyword
java");}
class A5{
}
void m(){
class Test1{
System.out.println(this);//prints same reference ID
public static void main(String args[]){
}
new A().getA().msg();
public static void main(String args[]){
}
A5 obj=new A5();
}
System.out.println(obj);//prints the reference ID
obj.m();
}
}
04/16/2024
Access Modifiers in Java
• There are two types of modifiers in Java: access modifiers and non-access modifiers.
• The access modifiers in Java specifies the accessibility or scope of a field, method,
constructor, or class.
• We can change the access level of fields, constructors, methods, and class by applying
the access modifier on it.
• There are four types of Java access modifiers:
• Private: The access level of a private modifier is only within the class. It cannot be accessed
from outside the class.
• Default: The access level of a default modifier is only within the package. It cannot be accessed
from outside the package. If you do not specify any access level, it will be the default.
• Protected: The access level of a protected modifier is within the package and outside the
package through child class. If you do not make the child class, it cannot be accessed from
outside the package.
• Public: The access level of a public modifier is everywhere. It can be accessed from within the
class, outside the class, within the package and outside the package.
04/16/2024
Understanding Java Access Modifiers
//Default
//Private //Role of Private Constructor //save by A.java
class A{ class A{ package pack;
private int data=40; private A(){}//private class A{
private void msg() constructor void msg()
{System.out.println("Hello void msg() {System.out.println("Hello");}
java");} {System.out.println("Hello }
} java");} //save by B.java
} package mypack;
public class Simple{ public class Simple{ import pack.*;
public static void main(String public static void main(String class B{
args[]){ args[]){ public static void main(String
A obj=new A(); A obj=new A();//Compile args[]){
Time Error A obj = new A();//Compile
System.out.println(obj.data);//C } Time Error
ompile Time Error } obj.msg();//Compile Time
obj.msg();//Compile Time
Error
Error
} }
}
}
04/16/2024
//PROTECTED //Public
//save by A.java //save by A.java
package pack;
public class A{ package pack;
protected void msg() public class A{
{System.out.println("Hello");} public void msg()
} {System.out.println("Hello");}
//save by B.java }
package mypack; //save by B.java
import pack.*;
package mypack;
class B extends A{ import pack.*;
public static void main(String args[]){
B obj = new B(); class B{
obj.msg(); public static void main(String args[]){
}
} A obj = new A();
obj.msg();
}
}
04/16/2024
Java String
• In Java, string is basically an object that represents sequence of char values.
An array of characters works same as Java string. For example:
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);
String s="javatpoint";
04/16/2024
CharSequence Interface
• The CharSequence interface is used to represent the sequence of characters.
String, StringBuffer and StringBuilder classes implement it. It means, we can
create strings in java by using these three classes.
• The Java String is immutable which means it cannot be changed. Whenever we
change any string, a new instance is created. For mutable strings, you can use
StringBuffer and StringBuilder classes.
04/16/2024
What is String in java
• Generally, String is a sequence of characters. But in Java, string is an object that
represents a sequence of characters. The java.lang.String class is used to create a string
object.
How to create a string object?
• There are two ways to create String object:
• By string literal
• By new keyword
String Literal
Java String literal is created by using double quotes. For Example:
String s="welcome";
• Each time you create a string literal, the JVM checks the "string constant pool" first.
• If the string already exists in the pool, a reference to the pooled instance is returned.
• If the string doesn't exist in the pool, a new string instance is created and placed in the
04/16/2024
pool. For example:
Why Java uses the concept of String literal?
• To make Java more memory efficient (because no new objects are created if it
exists already in the string constant pool).
By new keyword
String s=new String("Welcome");//creates two objects and one reference variable
In such case, JVM will create a new string object in normal (non-pool) heap
memory, and the literal "Welcome" will be placed in the string constant pool.
• The variable s will refer to the object in a heap (non-pool).
public class StringExample{
public static void main(String args[]){
String s1="java";//creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating java string by new keyword
System.out.println(s1);
System.out.println(s2);
04/16/2024 System.out.println(s3); }}
Java String class methods
N Method Description
o.
1 char charAt(int index) returns char value for the particular
index
2 int length() returns string length
3 static String format(String format, Object... args) returns a formatted string.
4 static String format(Locale l, String format, Object... args) returns formatted string with given
locale.
5 String substring(int beginIndex) returns substring for given begin
index.
6 String substring(int beginIndex, int endIndex) returns substring for given begin
index and end index.
7 boolean contains(CharSequence s) returns true or false after matching
the sequence of char value.
8 static String join(CharSequence delimiter, CharSequence... elements) returns a joined string.
9 static String join(CharSequence delimiter, Iterable<? extends returns a joined string.
CharSequence> elements)
04/16/2024
10 boolean equals(Object another) checks the equality of string with the given object.
11 boolean isEmpty() checks if string is empty.
12 String concat(String str) concatenates the specified string.
13 String replace(char old, char new) replaces all occurrences of the specified char value.
14 String replace(CharSequence old, CharSequence new) replaces all occurrences of the specified
CharSequence.
15 static String equalsIgnoreCase(String another) compares another string. It doesn't check case.
16 String[] split(String regex) returns a split string matching regex.
17 String[] split(String regex, int limit) returns a split string matching regex and limit.
18 String intern() returns an interned string.
19 int indexOf(int ch) returns the specified char value index.
20 int indexOf(int ch, int fromIndex) returns the specified char value index starting with
given index.
21 int indexOf(String substring) returns the specified substring index.
22 int indexOf(String substring, int fromIndex) returns the specified substring index starting with
given index.
23 String toLowerCase() returns a string in lowercase.
25 String toUpperCase() returns a string in uppercase.
26 String toUpperCase(Locale l) returns a string in uppercase using specified locale.
27 String trim() removes beginning and ending spaces of this string.
28 static String valueOf(int value) converts given type into string. It is an overloaded method.
04/16/2024
Java Character class
• The Character class generally wraps the value of all the primitive type char into an
object.
• Any object of the type Character may contain a single field whose type is char.
• All the fields, methods, and constructors of the class Character are specified by
the Unicode Data file which is particularly a part of Unicode Character Database
and is maintained by the Unicode Consortium.
• A set of characters ranging from U+0000 to U+FFFF is sometimes known as the
Basic Multilingual Plane(i.e. BMP).
• The characters whose codePoints are greater than U+FFFF are known as
supplementary characters.
• The Java language generally uses the UTF-16 encoding method to represent the
char arrays in String or String Buffer.
04/16/2024
04/16/2024
04/16/2024
04/16/2024
04/16/2024
04/16/2024
04/16/2024
04/16/2024
import java.util.Scanner; for (char ch2 : value2) {
public class JavaCharacterExample1 { int result2 = Character.hashCode(ch2);
public static void main(String[] args) { System.out.print("The hash code for the character '"+ch2+"'
// Ask the user for the first input. is given as:"+result2+"\n");
System.out.print("Enter the first input:"); }
// Use the Scanner class to get the user input. System.out.print("Enter the third input:");
Scanner scanner = new Scanner(System.in); char[] value3 = scanner.nextLine().toCharArray();
// Gets the user input. for (char ch3 : value3) {
char[] value1 = boolean result3 = Character.isDigit(ch3);
scanner.nextLine().toCharArray(); if(result3){
int result1 = 0; System.out.println("The character '" + ch3 + "' is a digit. ");
// Count the characters for a specific character.
for (char ch1 : value1) { }
result1 = Character.charCount(ch1); else{
} System.out.println("The character '" + ch3 + "' is not a digit.");
// Print the result. }
System.out.print("The value comes to: System.out.print("Enter the fourth input:");
"+result1+"\n"); char[] value4 = scanner.nextLine().toCharArray();
for (char ch4 : value4) {
System.out.print("Enter the second input:"); boolean result4 = Character.isISOControl(ch4);
char[] value2 = System.out.println("The fourth character '"+ch4+"' is an ISO
scanner.nextLine().toCharArray(); Control:"+result4); }}}}
04/16/2024
Java StringBuffer class
• Java StringBuffer class is used to create mutable (modifiable) string.
• The StringBuffer class in java is same as String class except it is mutable i.e. it can
be changed.
Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it simultaneously. So it is safe
and will result in an order.
04/16/2024
Important methods of StringBuffer class
Modifier and Type Method Description
public synchronized StringBuffer append(String s) is used to append the specified string with this string. The append()
method is overloaded like append(char), append(boolean), append(int),
append(float), append(double) etc.
public synchronized StringBuffer insert(int offset, String s) is used to insert the specified string with this string at the specified
position. The insert() method is overloaded like insert(int, char),
insert(int, boolean), insert(int, int), insert(int, float), insert(int, double)
etc.
public synchronized StringBuffer replace(int startIndex, int is used to replace the string from specified startIndex and endIndex.
endIndex, String str)
public synchronized StringBuffer delete(int startIndex, int is used to delete the string from specified startIndex and endIndex.
endIndex)
public synchronized StringBuffer reverse() is used to reverse the string.
public void ensureCapacity(int is used to ensure the capacity at least equal to the given minimum.
minimumCapacity)
public char charAt(int index) is used to return the character at the specified position.
public int length() is used to return the length of the string i.e. total number of characters.
public String substring(int beginIndex) is used to return the substring from the specified beginIndex.
public String substring(int beginIndex, int is used to return the substring from the specified beginIndex and
endIndex) endIndex.
04/16/2024
class StringBufferExample{ class StringBufferExample2{
public static void main(String args[]){ public static void main(String args[]){
StringBuffer sb=new StringBuffer sb=new StringBuffer("Hello ");
StringBuffer("Hello "); sb.insert(1,"Java");//now original string is
sb.append("Java");//now original string changed
is changed System.out.println(sb);//prints HJavaello
System.out.println(sb);//prints Hello }
Java }
}
class StringBufferExample3{
class StringBufferExample4{
public static void main(String args[]){
public static void main(String args[]){
StringBuffer sb=new
StringBuffer sb=new StringBuffer("Hello");
StringBuffer("Hello");
sb.delete(1,3);
sb.replace(1,3,"Java");
System.out.println(sb);//prints Hlo
System.out.println(sb);//prints HJavalo
}
}
}
}
04/16/2024
class StringBufferExample5{ class StringBufferExample6{
public static void main(String args[]){ public static void main(String args[]){
StringBuffer sb=new StringBuffer sb=new StringBuffer();
StringBuffer("Hello"); System.out.println(sb.capacity());//default 16
sb.reverse(); sb.append("Hello");
System.out.println(sb);//prints olleH System.out.println(sb.capacity());//now 16
} sb.append("java is my favourite language");
} System.out.println(sb.capacity());//now (16*2)+2=34
i.e (oldcapacity*2)+2
class StringBufferExample7{ }
public static void main(String args[]){ }
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default System.out.println(sb.capacity());//now
16 (16*2)+2=34 i.e (oldcapacity*2)+2
sb.append("Hello"); sb.ensureCapacity(10);//now no change
System.out.println(sb.capacity());//now
16 System.out.println(sb.capacity());//now
sb.append("java is my favourite 34
language"); sb.ensureCapacity(50);//now (34*2)+2
System.out.println(sb.capacity());//now
04/16/2024 70 } }
Java File Class
• The File class is an abstract representation of file and directory pathname. A
pathname can be either absolute or relative.
• The File class have several methods for working with directories and files such as
creating new directories or files, deleting and renaming directories or files, listing
the contents of a directory etc.
Fields
Modifier Type Field Description
static String pathSeparator It is system-dependent path-separator character, represented
as a string for convenience.
static char pathSeparatorChar It is system-dependent path-separator character.
static String separator It is system-dependent default name-separator character,
represented as a string for convenience.
static char separatorChar It is system-dependent default name-separator character.
04/16/2024
Constructors
Constructor Description
File(File parent, String child) It creates a new File instance from a parent
abstract pathname and a child pathname
string.
File(String pathname) It creates a new File instance by converting
the given pathname string into an abstract
pathname.
File(String parent, String child) It creates a new File instance from a parent
pathname string and a child pathname
string.
File(URI uri) It creates a new File instance by converting
the given file: URI into an abstract
pathname.
04/16/2024
Useful Methods
Modifier Method Description
and Type
static File createTempFile(String prefix, It creates an empty file in the default temporary-file directory, using the given
String suffix) prefix and suffix to generate its name.
boolean createNewFile() It atomically creates a new, empty file named by this abstract pathname if and only
if a file with this name does not yet exist.
boolean canWrite() It tests whether the application can modify the file denoted by this abstract
pathname.String[]
boolean canExecute() It tests whether the application can execute the file denoted by this abstract
pathname.
boolean canRead() It tests whether the application can read the file denoted by this abstract pathname.
boolean isAbsolute() It tests whether this abstract pathname is absolute.
boolean isDirectory() It tests whether the file denoted by this abstract pathname is a directory.
boolean isFile() It tests whether the file denoted by this abstract pathname is a normal file.
String getName() It returns the name of the file or directory denoted by this abstract pathname.
String getParent() It returns the pathname string of this abstract pathname's parent, or null if this
pathname does not name a parent directory.
04/16/2024
Path toPath() It returns a java.nio.file.Path object constructed from the this abstract
path.
URI toURI() It constructs a file: URI that represents this abstract pathname.
File[] listFiles() It returns an array of abstract pathnames denoting the files in the directory
denoted by this abstract pathname
long getFreeSpace() It returns the number of unallocated bytes in the partition named by this
abstract path name.
String[] list(FilenameFilter filter) It returns an array of strings naming the files and directories in the directory
denoted by this abstract pathname that satisfy the specified filter.
boolean mkdir() It creates the directory named by this abstract pathname.
04/16/2024
import java.io.*; import java.io.*;
public class FileExample { public class FileExample {
public static void main(String[] args) { public static void main(String[] args) {
File f=new File dir=new File("/Users/sonoojaiswal/Documents");
File("/Users/sonoojaiswal/Documents"); File files[]=dir.listFiles();
for(File file:files){
String filenames[]=f.list(); System.out.println(file.getName()+" Can Write:
for(String filename:filenames){ "+file.canWrite()+"
System.out.println(filename); Is Hidden: "+file.isHidden()+" Length: "+file.length()+"
} bytes");
} }
} }
}
04/16/2024
CASE STUDY – STUDENT GRAD CALCULATION
1) This case study calculates the grade of a student based on the marks entered by user in each
04/16/2024
Public class JavaExample System.out.print("The student Grade is: ");
{ if(avg>=80)
public static void main(String args[]) { System.out.print("A");
{ }
int marks[] = new int[6]; else if(avg>=60 && avg<80)
int i; {
float total=0, avg; System.out.print("B");
Scanner scanner = new Scanner(System.in); }
for(i=0; i<6; i++) else if(avg>=40 && avg<60)
{ {
System.out.print("Enter Marks of Subject"+ System.out.print("C");
(i+1)+":"); marks[i] = scanner.nextInt(); }
total = total + marks[i]; else
} {
scanner.close(); //Calculating average here System.out.print("D");
avg = total/6; }
}}
04/16/2024
RESULT
04/16/2024
NPTEL LINK
https://nptel.ac.in/courses/106/106/106106147/
https://www.youtube.com/watch?v=OjdT2l-EZJA&list=PLfn3cNtmZdPOe3R_
wO_h540QNfMkCQ0ho
04/16/2024
References
1. Herbert Schildt, Java The Complete Reference, 7 /9th Edition, Tata McGraw Hill, 2007.
2. https://www.geeksforgeeks.org
3. www.slideshare.net
4. https://www.javatpoint.com/
5. https://www.w3schools.com/java/
6. https://www.edureka.co
7. https://www.softwaretestinghelp.com
04/16/2024