0% found this document useful (0 votes)
122 views32 pages

Cc103 Midterm

The document discusses different types of loops in Java including while, do-while, for, and enhanced for loops. It provides the syntax and examples of each loop type. The while loop executes statements as long as a Boolean expression is true. The do-while loop is similar but guarantees the statements execute at least once. The for loop allows efficiently writing a loop that repeats a specific number of times, with initialization, Boolean expression, and update components. The enhanced for loop is used to loop through arrays.

Uploaded by

Michyll Kyut
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
122 views32 pages

Cc103 Midterm

The document discusses different types of loops in Java including while, do-while, for, and enhanced for loops. It provides the syntax and examples of each loop type. The while loop executes statements as long as a Boolean expression is true. The do-while loop is similar but guarantees the statements execute at least once. The for loop allows efficiently writing a loop that repeats a specific number of times, with initialization, Boolean expression, and update components. The enhanced for loop is used to loop through arrays.

Uploaded by

Michyll Kyut
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 32

INFORMATION SHEET MD-1.1.

1 MODULE 6
“Java Decision Making”
Java Decision Making
There are two types of decision making statements in Java. They are:
 if statements
 switch statements
The if Statement:
An if statement consists of a Boolean expression followed by one or more statements.
Syntax:
The syntax of an if statement is:
if(Boolean_expression)
{
//Statements will execute if the Boolean expression is true
}
If the Boolean expression evaluates to true then the block of code inside the if statement will be
executed. If not the first set of code after the end of the if statement (after the closing curly brace) will
be executed.

This would produce the following result:


Thisisif statement

The if...else Statement:


An if statement can be followed by an optional else statement, which executes when the Boolean
expression is false.
Syntax:
The syntax of an if...else is:
if(Boolean_expression){
//Executes when the Boolean expression is true
}else{
//Executes when the Boolean expression is false
}
Example:

This would produce the following result:


Thisiselse statement

The if...else if...else Statement:


An if statement can be followed by an optional else if...else statement, which is very useful to test
various conditions using single if...else if statement.
When using if , else if , else statements there are few points to keep in mind.
 An if can have zero or one else's and it must come after any else if's.
 An if can have zero to many else if's and they must come before the else.
 Once an else if succeeds, none of the remaining else if's or else's will be tested.
Syntax:
The syntax of an if...else is:
if(Boolean_expression1){
//Executes when the Boolean expression 1 is true
}elseif(Boolean_expression2){
//Executes when the Boolean expression 2 is true
}elseif(Boolean_expression3){
//Executes when the Boolean expression 3 is true
}else{
//Executes when the none of the above condition is true.
}
Example:
This would produce the following result:
Value of X is30

Nested if...else Statement:


It is always legal to nest if-else statements which means you can use one if or else if statement inside
another if or else if statement.
Syntax:
The syntax for a nested if...else is as follows:
if(Boolean_expression1){
//Executes when the Boolean expression 1 is true
if(Boolean_expression2){
//Executes when the Boolean expression 2 is true
}
}
You can nest else if...else in the similar way as we have nested if statement.
Example:

This would produce the following result:

X =30and Y =10
The switch Statement:
A switch statement allows a variable to be tested for equality against a list of values. Each value is called
a case, and the variable being switched on is checked for each case.
Syntax:
The syntax of enhanced for loop is:
switch(expression){
casevalue :
//Statements
break;//optional
casevalue :
//Statements
break;//optional
//You can have any number of case statements.
default://Optional
//Statements
}
The following rules apply to a switch statement:
 The variable used in a switch statement can only be a byte, short, int, or char.
 You can have any number of case statements within a switch. Each case is followed by the value
to be compared to and a colon.
 The value for a case must be the same data type as the variable in the switch and it must be a
constant or a literal.
 When the variable being switched on is equal to a case, the statements following that case will
execute until a break statement is reached.
 When a break statement is reached, the switch terminates, and the flow of control jumps to the
next line following the switch statement.
 Not every case needs to contain a break. If no break appears, the flow of control will fall
throught o subsequent cases until a break is reached.
 A switch statement can have an optional default case, which must appear at the end of the
switch. The default case can be used for performing a task when none of the cases is true. No
break is needed in the default case.

Example:

Compile and run above program using various command line arguments. This would produce the
following result:
$ javaTest
Welldone
Your grade is a C
$

SELF-CHECK MD-1.1-1
A. Fill in the blanks with the correct answer.

1. The ___________________ and ____________________ are two types decision making


statement in java.
2. A _____________ statement allows a variable to be tested for equality against a list of values.
3. When a ________________ is reached, the switch terminates, and the flow of control jumps to
the next line following the switch statement
4. You can have any number of case statements within a switch. Each case is followed by the value
to be compared to and a ________.

SELF-CHECK ANSWER KEY MD-1.1.1


1. If statements and switch statements
2. Switch statements
3. Break statement
4. colon
INFORMATION SHEET MD-2.1.1 MODULE 7
“Java Loops - for, while and do...while”

There may be a situation when we need to execute a block of code several number of times, and is often
referred to as a loop.
Java has very flexible three looping mechanisms. You can use one of the following three loops:
 while Loop
 do...while Loop
 for Loop
As of Java 5, the enhanced for loop was introduced. This is mainly used for Arrays.

The while Loop:


A while loop is a control structure that allows you to repeat a task a certain number of times.

Syntax:
The syntax of a while loop is:
while(Boolean_expression)
{
//Statements
}

When executing, if the boolean_expression result is true, then the actions inside the loop will be
executed. This will continue as long as the expression result is true.
Here, key point of the while loop is that the loop might not ever run. When the expression is tested and
the result is false, the loop body will be skipped and the first statement after the while loop will be
executed.

Example:

This would produce the following result:


value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

The do...while Loop:


A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute
at least one time.

Syntax:
The syntax of a do...while loop is:
do
{
//Statements
}while(Boolean_expression);

Notice that the Boolean expression appears at the end of the loop, so the statements in the loop
execute once before the Boolean is tested.
If the Boolean expression is true, the flow of control jumps back up to do, and the statements in the
loop execute again. This process repeats until the Boolean expression is false.

Example:

This would produce the following result:


value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

The for Loop:


A for loop is a repetition control structure that allows you to efficiently write a loop that needs
to execute a specific number of times.
A for loop is useful when you know how many times a task is to be repeated.

Syntax:
The syntax of a for loop is:
for(initialization;Boolean_expression; update)
{
//Statements
}

Here is the flow of control in a for loop:


 The initialization step is executed first, and only once. This step allows you to declare and
initialize any loop control variables. You are not required to put a statement here, as long as a
semicolon appears.
 Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is
false, the body of the loop does not execute and flow of control jumps to the next statement
past the for loop.
 After the body of the for loop executes, the flow of control jumps back up to the update
statement. This statement allows you to update any loop control variables. This statement can
be left blank, as long as a semicolon appears after the Boolean expression.
 The Boolean expression is now evaluated again. If it is true, the loop executes and the process
repeats itself (body of loop, then update step, then Boolean expression). After the Boolean
expression is false, the for loop terminates.
Example:

This would produce the following result:


value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

Enhanced for loop in Java:


As of Java 5, the enhanced for loop was introduced. This is mainly used for Arrays.

Syntax:
The syntax of enhanced for loop is:
for(declaration : expression)
{
//Statements
}
 Declaration: The newly declared block variable, which is of a type compatible with the elements
of the array you are accessing. The variable will be available within the for block and its value
would be the same as the current array element.
 Expression: This evaluates to the array you need to loop through. The expression can be an
array variable or method call that returns an array.
Example:

This would produce the following result:


10,20,30,40,50,
James,Larry,Tom,Lacy,

The break Keyword:


The break keyword is used to stop the entire loop. The break keyword must be used inside any
loop or a switch statement.
The break keyword will stop the execution of the innermost loop and start executing the next
line of code after the block.

Syntax:
The syntax of a break is a single statement inside any loop:
break; Example:
This would produce the following result:
10
20
The continue Keyword:

The continue keyword can be used in any of the loop control structures. It causes the loop to
immediately jump to the next iteration of the loop.
 In a for loop, the continue keyword causes flow of control to immediately jump to the update
statement.
 In a while loop or do/while loop, flow of control immediately jumps to the Boolean expression.

Syntax:
The syntax of a continue is a single statement inside any loop:
continue;

Example:

This would produce the following result:


10
20
40
50
SELF CHECK MD-2.1.1
Identification: Identify the following:
1. ___________ keyword can be used in any of the loop control structures.
2. ___________ keyword is used to stop the entire loop
3. ___________ is useful when you know how many times a task is to be repeated
4. ___________ The newly declared block variable, which is of a type compatible with the
elements of the array you are accessing.
5. ___________ This evaluates to the array you need to loop through
SELF-CHECK ANSWER KEY MD-2.1.1
1. Continue
2. Break
3. For loop
4. Declaration
5. Expression

INFORMATION SHEET MD-3.1.1 MODULE 8


“Java Break, Arrays and Continue”
Java Break

You have already seen the break statement used in an earlier chapter of this tutorial. It was used to
"jump out" of a switch statement.

The break statement can also be used to jump out of a loop.

This example jumps out of the loop when i is equal to 4:

Example:

for (int i = 0; i< 10; i++) {

if (i == 4) {

break;

System.out.println(i);

Result:

Java Continue
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues
with the next iteration in the loop.

This example skips the value of 4:


Example:
for (int i = 0; i< 10; i++) {
if (i == 4) {
continue;
}
System.out.println(i);
}
Result:
0
1
2
3
5
6
7
8
9

Break and Continue in While Loop

You can also use break and continue in while loops:


Break Example
int i = 0;
while (i< 10) {
System.out.println(i);
i++;
if (i == 4) {
break;
}
}
Result:
0
1
2
3

Continue Example
int i = 0;
while (i< 10) {
if (i == 4) {
i++;
continue;
}
System.out.println(i);
i++;
}
Result:
0
1
2
3
5
6
7
8
9

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;
We have now declared a variable that holds an array of strings. To insert values to it, we can use an
array literal - place the values in a comma-separated list, inside curly braces:
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
To create an array of integers, you could write:
int[] myNum = {10, 20, 30, 40};

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:
Example
public class MyClass{
public static void main(String[]args){
String[] cars ={"Volvo","BMW","Ford","Mazda"};
System.out.println(cars[0]);
}
}
Result:
Volvo

Note: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.

Change an Array Element


To change the value of a specific element, refer to the index number:
Example
cars[0] = "Opel";

Example
public class MyClass{
public static void main(String[]args){
String[] cars ={"Volvo","BMW","Ford","Mazda"};
cars[0]="Opel";
System.out.println(cars[0]);
}
}
// Now outputs Opel instead of Volvo

Array Length

To find out how many elements an array has, use the length property:
Example
public class MyClass{
public static void main(String[]args){
String[] cars ={"Volvo","BMW","Ford","Mazda"};
System.out.println(cars.length);
}
}
// Outputs 4

Loop Through an Array


You can loop through the array elements with the for loop, and use the length property to specify how
many times the loop should run.
The following example outputs all elements in the cars array:
Example
public class MyClass{
public static void main(String[]args){
String[] cars ={"Volvo","BMW","Ford","Mazda"};
for(int i=0;i<cars.length;i++){
System.out.println(cars[i]);
}
}
}

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) {
...
}
The following example outputs all elements in the cars array, using a "for-each" loop:
Example
public class MyClass{
public static void main(String[]args){
String[] cars ={"Volvo","BMW","Ford","Mazda"};
for(String i: cars){
System.out.println(i);
}
}
}
Results:
Volvo
BMW
Ford
Mazda
The example above can be read like this: for each String element (called i - as in index) in cars, print out
the value of i.
If you compare the for loop and for-each loop, you will see that the for-each method is easier to write, it
does not require a counter (using the length property), and it is more readable.

Multidimensional Arrays
A multidimensional array is an array containing one or more arrays.
To create a two-dimensional array, add each array within its own set of curly braces:
Example
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
myNumbers is now an array with two arrays as its elements.
To access the elements of the myNumbers array, specify two indexes: one for the array, and one for the
element inside that array. This example accesses the third element (2) in the second array (1) of
myNumbers:
Example
public class MyClass{
public static void main(String[]args){
int[][]myNumbers={{1,2,3,4},{5,6,7}};
int x =myNumbers[1][2];
System.out.println(x);
}
}
Result: 7
We can also use a for loop inside another for loop to get the elements of a two-dimensional array (we
still have to point to the two indexes):
Example
public class MyClass{
public static void main(String[]args){
int[][]myNumbers={{1,2,3,4},{5,6,7}};
for(inti=0;i<myNumbers.length;++i){
for(int j =0; j <myNumbers[i].length;++j){
System.out.println(myNumbers[i][j]);
}
}
}
}
Result:
1
2
3
4
5
6
7

SELF CHECK MD-3-1-1


Give the output of the following program code:

A.

B.

SELF-CHECK ANSWER KEY MD-3.1.1


A. 10
B. Volvo BMW Ford Mazda

INFORMATION SHEET MD-4.1.1 MODULE 9


“Java Methods”

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


 You can pass data, known as parameters, into a method.
 Methods are used to perform certain actions, and they are also known as functions.
 Why use methods? To reuse code: define the code once, and use it many times.
Create a Method

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

Example

Create a method inside MyClass:

public class MyClass {

static void myMethod() {

// code to be executed

Example Explained:

 myMethod() is the name of the method


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

Call a Method

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

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

Example
Inside main, call the myMethod() method:
public class MyClass {
static void myMethod() {
System.out.println("I just got executed!");
}

public static void main(String[] args) {


myMethod();
}
}
Outputs "I just got executed!"

A method can also be called multiple times:

Example
public class MyClass {
static void myMethod() {
System.out.println("I just got executed!");
}

public static void main(String[] args) {


myMethod();
myMethod();
myMethod();
}
}

Results:
I just got executed!
I just got executed!
I just got executed!

Java Method Parameters

Parameters and Arguments

 Information can be passed to methods as 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:

Example
public class MyClass {
static void myMethod(String fname) {
System.out.println(fname + " Refsnes");
}

public static void main(String[] args) {


myMethod("Liam");
myMethod("Jenny");
myMethod("Anja");
}
}
Results:
Liam Refsnes
Jenny Refsnes
Anja Refsnes
When a parameter is passed to the method, it is called an argument. So, from the example above:
fname is a parameter, while Liam, Jenny and Anja are arguments.

Multiple Parameters

You can have as many parameters as you like:

Example:
public class MyClass {
static void myMethod(String fname, int age) {
System.out.println(fname + " is " + age);
}

public static void main(String[] args) {


myMethod("Liam", 5);
myMethod("Jenny", 8);
myMethod("Anja", 31);
}
}
Results:
Liam is 5
Jenny is 8
Anja is 31

Note that when you are working with multiple parameters, the method call must have the same number
of arguments as there are parameters, and the arguments must be passed in the same order.

Return Values

The void keyword, used in the examples above, indicates that the method should not return a value. 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:

Example:
public class MyClass {
static int myMethod(int x) {
return 5 + x;
}
public static void main(String[] args) {
System.out.println(myMethod(3));
}
}
Results:
Outputs 8 (5 + 3)

This example returns the sum of a method's two parameters:

Example:
public class MyClass {
static int myMethod(int x, int y) {
return x + y;
}

public static void main(String[] args) {


System.out.println(myMethod(5, 3));
}
}
Results:
Outputs 8 (5 + 3)

You can also store the result in a variable (recommended, as it is easier to read and maintain):

Example
public class MyClass {
static int myMethod(int x, int y) {
return x + y;
}

public static void main(String[] args) {


int z = myMethod(5, 3);
System.out.println(z);
}
}
Results:
// Outputs 8 (5 + 3)

A Method with If...Else

It is common to use if...else statements inside methods:

Example
public class MyClass {
// Create a checkAge() method with an integer variable called age
static void checkAge(int age) {

// If age is less than 18, print "access denied"


if (age < 18) {
System.out.println("Access denied - You are not old enough!");

// If age is greater than 18, print "access granted"


} else {
System.out.println("Access granted - You are old enough!");
}

public static void main(String[] args) {


checkAge(20); // Call the checkAge method and pass along an age of 20
}
}
Results:
// Outputs "Access granted - You are old enough!"

Java Method Overloading

Method Overloading

With method overloading, multiple methods can have the same name with different parameters:

Example:
int myMethod(int x)
float myMethod(float x)
double myMethod(double x, double y)

Consider the following example, which have two methods that add numbers of different type:

Example
static int plusMethodInt(int x, int y) {
return x + y;
}
static double plusMethodDouble(double x, double y) {
return x + y;
}
public static void main(String[] args) {
int myNum1 = plusMethodInt(8, 5);
double myNum2 = plusMethodDouble(4.3, 6.26);
System.out.println("int: " + myNum1);
System.out.println("double: " + myNum2);
}
Result:
int: 13
double: 10.559999999999999

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:

Example
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);
}
Result:
int: 13
double: 10.559999999999999
Note: Multiple methods can have the same name as long as the number and/or type of parameters are
different.

SELF CHECK MD 4.1.1

1. Insert the missing part to call myMethod from main.

static void myMethod() {


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

public static void main(String[] args) {


;
}

2. Add a fname parameter of type String to myMethod, and output "John Doe":

static void myMethod( ) {


System.out.println( + " Doe");
}

public static void main(String[] args) {


myMethod("John");
}

SELF-CHECK ANSWER KEY MD-4.1.1


1.

static void myMethod() {


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

public static void main(String[] args) {


myMethod();
}

2.

static void myMethod(String fname) {


System.out.println(fname + " Doe");
}

public static void main(String[] args) {


myMethod("John");
}
INFORMATION SHEET MD-5.1.1 MODULE 10
“Java Packages and Files”

Java Packages & API

A package in Java is used to group related classes. Think of it as a folder in a file directory. We
use packages to avoid name conflicts, and to write a better maintainable code. Packages are divided into
two categories:

 Built-in Packages (packages from the Java API)


 User-defined Packages (create your own packages)
Built-in Packages

The Java API is a library of prewritten classes, that are free to use, included in the Java
Development Environment.

The library contains components for managing input, database programming, and much much
more. The complete list can be found at Oracles website: https://docs.oracle.com/javase/8/docs/api/.

The library is divided into packages and classes. Meaning you can either import a single class
(along with its methods and attributes), or a whole package that contain all the classes that belong to
the specified package.

To use a class or a package from the library, you need to use the import keyword:

Syntax:
import package.name.Class; // Import a single class
import package.name.*; // Import the whole package

Import a Class

If you find a class you want to use, for example, the Scanner class, which is used to get user
input, write the following code:

Example

import java.util.Scanner;

In the example above, java.util is a package, while Scanner is a class of the java.util package.
To use the Scanner class, create an object of the class and use any of the available methods
found in the Scanner class documentation. In our example, we will use the nextLine() method, which is
used to read a complete line:

Example

Using the Scanner class to get user input:

Import a Package

There are many packages to choose from. In the previous example, we used the Scanner class
from the java.util package. This package also contains date and time facilities, random-number
generator and other utility classes.

To import a whole package, end the sentence with an asterisk sign (*). The following example
will import ALL the classes in the java.util package:

Example:
import java.util.Scanner;
User-defined Packages
To create your own package, you need to understand that Java uses a file system directory to store
them. Just like folders on your computer:
Example
└── root
└── mypack
└── MyPackageClass.java

To create a package, use the package keyword:


MyPackageClass.java
package mypack;
class MyPackageClass {
public static void main(String[] args) {
System.out.println("This is my package!");
}
}

Save the file as MyPackageClass.java, and compile it:


C:\Users\Your Name>javac MyPackageClass.java

Then compile the package:


C:\Users\Your Name>javac -d . MyPackageClass.java

This forces the compiler to create the "mypack" package.


The -d keyword specifies the destination for where to save the class file. You can use any directory
name, like c:/user (windows), or, if you want to keep the package within the same directory, you can use
the dot sign ".", like in the example above.
Note:  The package name should be written in lower case to avoid conflict with class names.
When we compiled the package in the example above, a new folder was created, called "mypack".
To run the MyPackageClass.java file, write the following:
C:\Users\Your Name>java mypack.MyPackageClass
The output will be:
This is my package!

“Java Files”

 File handling is an important part of any application.


 Java has several methods for creating, reading, updating, and deleting files.

Java File Handling

 The File class from the java.io package, allows us to work with files.
 To use the File class, create an object of the class, and specify the filename or directory name:

Example
import java.io.File; // Import the File class
File myObj = new File("filename.txt"); // Specify the filename

The File class has many useful methods for creating and getting information about files. For example:

Method Type Description

canRead() Boolean Tests whether the file is readable or not

canWrite() Boolean Tests whether the file is writable or not

createNewFile() Boolean Creates an empty file

delete() Boolean Deletes a file

exists() Boolean Tests whether the file exists

getName() String Returns the name of the file

getAbsolutePath(
String Returns the absolute pathname of the file
)

length() Long Returns the size of the file in bytes


list() String[] Returns an array of the files in the directory

mkdir() Boolean Creates a directory

“Java Create and Write To Files”

Create a File
To create a file in Java, you can use the createNewFile() method. This method returns a
boolean value: true if the file was successfully created, and false if the file already exists. Note that the
method is enclosed in a try...catch block. This is necessary because it throws an IOException if an error
occurs (if the file cannot be created for some reason):

Example
import java.io.File; // Import the File class
import java.io.IOException; // Import the IOException class to handle errors

public class CreateFile {


public static void main(String[] args) {
try {
File myObj = new File("filename.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}

The output will be:

File created: filename.txt

To create a file in a specific directory (requires permission), specify the path of the file and use double
backslashes to escape the "\" character (for Windows). On Mac and Linux you can just write the path,
like: /Users/name/filename.txt

Example
File myObj = new File("C:\\Users\\MyName\\filename.txt");
Write To a File
In the following example, we use the FileWriter class together with its write() method to write some
text to the file we created in the example above. Note that when you are done writing to the file, you
should close it with the close() method:
Example
import java.io.FileWriter; // Import the FileWriter class
import java.io.IOException; // Import the IOException class to handle errors

public class WriteToFile {


public static void main(String[] args) {
try {
FileWriter myWriter = new FileWriter("filename.txt");
myWriter.write("Files in Java might be tricky, but it is fun enough!");
myWriter.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}

The output will be:


Successfully wrote to the file.

“Java Read Files”


Read a File
In the following example, we use the Scanner class to read the contents of the text file we created in
the previous chapter:
Example
import java.io.File; // Import the File class
import java.io.FileNotFoundException; // Import this class to handle errors
import java.util.Scanner; // Import the Scanner class to read text files
public class ReadFile {
public static void main(String[] args) {
try {
File myObj = new File("filename.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
System.out.println(data);
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
The output will be:
Files in Java might be tricky, but it is fun enough!

Get File Information


To get more information about a file, use any of the File methods:
Example
import java.io.File; // Import the File class

public class GetFileInfo {


public static void main(String[] args) {
File myObj = new File("filename.txt");
if (myObj.exists()) {
System.out.println("File name: " + myObj.getName());
System.out.println("Absolute path: " + myObj.getAbsolutePath());
System.out.println("Writeable: " + myObj.canWrite());
System.out.println("Readable " + myObj.canRead());
System.out.println("File size in bytes " + myObj.length());
} else {
System.out.println("The file does not exist.");
}
}
}

The output will be:


File name: filename.txt
Absolute path: C:\Users\MyName\filename.txt
Writeable: true
Readable: true
File size in bytes: 0

SELF CHECK MD-5-1-1


Identification: Identify the following:
1. ___________ Tests whether the file exists
2. ___________ Returns the size of the file in bytes
3. ___________ Deletes a file
4. ___________ Returns an array of the files in the directory
5. ___________ Tests whether the file is readable or not
6. ___________ Creates an empty file
7. ___________ Tests whether the file is writable or not
8. ___________ Returns the absolute pathname of the file
9. ___________ Creates a directory
10. ___________ Returns the name of the file
SELF-CHECK ANSWER KEY MD-5.1.1
1. exists()
2. length()
3. delete()
4. list()
5. canRead()
6. createNewFile()
7. canWrite()
8. getAbsolutePath()
9. mkdir()
10. getName()

You might also like