Java
Java
______________________________________________________________________________
Code:
Output:
HELLO WORLD PROGRAM
______________________________________________________________________________
Explanation:
This is the first line of the Hello World program. Every java application must have at least one
class definition that consists of class keyword followed by class name. Keyword should not be
changed, it should use it as it is. However the class name can be anything.
This is the next line in the program, the following are the explanation for each word:
public: This makes the main method public that means that we can call the method from outside
the class.
static: We do not need to create object for static methods to run. They can run itself.
main: It is the method name. This is the entry point method from which the JVM can run a
program.
(String[] args): Used for command line arguments that are passed as strings.
System.out.println("Hello World");
This method prints the contents inside the double quotes into the console and inserts a newline
after.
CALCULATE AREA OF CIRCLE IN A STATIC METHOD
______________________________________________________________________________
Code:
importjava.util.Scanner;
classAreaOfCircle
{
public static void main(String args[])
{
Output:
CALCULATE AREA OF CIRCLE IN A STATIC METHOD
______________________________________________________________________________
Explanation:
But , if you were written like that , then the system will won’t understand , until and unless you
assign the value of “PIE” is 22/7. As usual , you always represent the values in binary numbers.
The system can’t able to understand whether the given number is a number , or given letter is a
letter. All it understood as ” Character ” or just a “ Symbol “. Here goes the complete step by
step explanation of above code and how it works.
Step : 1 –
import java.util.Scanner;
1
( here ‘import’ is a keyword in java used to get features from inbult packages . here we using a
package called util it consist of many classes and we using one of the class Scanner to get
command over console which is interface between user and program. )
Step – 3 :
Step -4 :
so to get access on console we want create a object Syntax:new Scanner(); after creating object
that reference will store in variable ‘s’ )
Step – 5 :
Step – 6 :
double r= s.nextDouble();
1
( here above instruction is get input in requiredformat. first we want to know about
nextDouble() method it takes a token(collection of symbols divide by white space
example:”ABC”, “DEF” , “GHI”,”10″,”20″)
which is given by user.when user give 10 as input acutally in user perspective it is number but
any number or string which entered on console by default those are strings ,so 1o as string
but we want 10 as number format for that we have method to convert string to
number(Int,Double,Float,Long…..) some of those method are:
1.nextDouble() ,
2 nextFloat(),
3.nextInt(),
4.nextLong()
5.nextShort()
6.next() or nextString() ).
Step – 7 :
double area=(22*r*r)/7 ;
1
Step – 8 : System.out.println(“Area of Circle is: ” + area); ( Once, you entered the radius , the
value stored in a particular function ( nextDouble(); ) and read those values with the help of a
scanner and display the output for a given value.
A : The major difference is where double can represent the output even after the decimal point ,
whereas in ” Int ” only the numbers before decimal point will take into consideration.
Code:
/*
* Test Arithmetic Operations
*/
public class ArithmeticTest { // Save as "ArithmeticTest.java"
public static void main(String[] args) {
int number1 = 98; // Declare an int variable number1 and initialize it to 98
int number2 = 5; // Declare an int variable number2 and initialize it to 5
int sum, difference, product, quotient, remainder; // Declare 5 int variables to hold results
// Print results
System.out.print("The sum, difference, product, quotient and remainder of "); // Print description
System.out.print(number1); // Print the value of the variable
System.out.print(" and ");
System.out.print(number2);
System.out.print(" are ");
System.out.print(sum);
System.out.print(", ");
System.out.print(difference);
System.out.print(", ");
System.out.print(product);
System.out.print(", ");
System.out.print(quotient);
System.out.print(", and ");
System.out.println(remainder);
______________________________________________________________________________
Output:
Explanation:
Declare all the variables number1, number2, sum, difference, product, quotient and remainder
needed in this program. All variables are of the type int (integer).
Carry out the arithmetic operations on number1 and number2. Take note that division of two
integers produces a truncated integer, e.g., 98/5 → 19, 99/4 → 24, and 1/2 → 0.
The following prints the results of the arithmetic operations, with the appropriate string
descriptions in between. Take note that text strings are enclosed within double-quotes, and will
get printed as they are, including the white spaces but without the double quotes. To print
the value stored in a variable, no double quotes should be used. For example,
The following illustrates the increment and decrement operations. Unlike '+', '-', '*', '/' and '%',
which work on two operands (binary operators), '++' and '--' operate on only one operand (unary
operators). ++x is equivalent to x = x + 1, i.e., increment x by 1.
++number1;
--number2;
The following prints the new values stored after the increment/decrement operations. Take note
that instead of using many print() statements as in Lines 18-31, we could simply place all the
items (text strings and variables) into one println(), with the items separated by '+'. In this
case, '+' does not perform addition. Instead, it concatenates or joins all the items together.
Code:
class Addition {
int a = 5, b = 17, c = 0;
c = a + b;
______________________________________________________________________________
Output:
______________________________________________________________________________
Explanation:
This program has two variables which have already contain values and sum of these numbers
store in third variable.
Code:
inti = 10;
int j = 10;
i++;
j++;
int k = i++;
int l = ++j;
______________________________________________________________________________
Output:
Explanation:
This program shows how to use Java increment operator (++) and decrement (--) operator.
The increment and decrement operators can be used in two ways, postfix and prefix. In normal
use, both form behaves the same way but when they are part of expression, there is difference
between these two forms.
When prefix form is used the operands incremented or decremented before substituting its value
while when the postfix form is used the operand’s old value is used to evaluate the expression.
The value of ion this program would be assigned to k and then it’s incremented by one. The
value of j would be incremented first and then assigned to k.
MODULUS OPERATOR
______________________________________________________________________________
Code:
inti = 50;
double d = 32;
______________________________________________________________________________
Output:
MODULUS OPERATOR
______________________________________________________________________________
Explanation:
In this program, the modulus operator returns remainder of the division of floating point or
integer types.
SWITCH STATEMENT
______________________________________________________________________________
Code:
switch (i) {
case 0:
System.out.println("i is 0");
break;
case 1:
System.out.println("i is 1");
break;
case 2:
System.out.println("i is 2");
break;
default:
SWITCH STATEMENT
______________________________________________________________________________
Output:
______________________________________________________________________________
Explanation:
This program shows how to use switch statement in a Java program. Switch statement is a better
replacement if multiple if else if statements.
The 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.
The expression must be of type int, short, byte or char while the values should be constants
literal values and cannot be duplicated.
Expression value is compared with each case value. If itmatches, statements following
case would be executed. Break statement is used to terminate the execution ofstatements.
If none of the case matches, statements following defaultwould be executed.
If break statement is not used within case, all cases following matching cases would be
executed.
FREE FLOWING SWITCH STATEMENT
______________________________________________________________________________
Code:
inti = 0;
switch (i) {
case 0:
System.out.println("i is 0");
case 1:
System.out.println("i is 1");
case 2:
System.out.println("i is 2");
default:
}
FREE FLOWING SWITCH STATEMENT
______________________________________________________________________________
Output:
______________________________________________________________________________
Explanation:
This program shows how case statements are executed if break is not used to terminate the
execution of the statements.
A free flowing switch statement is a switch statement where break statement is not specified,
thus all cases after the matching one (including the default) will be executed. In short, to create a
free flowing switch statement you should:
Create a switch statement that evaluates an expression. The switch statement evaluates its
expression, then executes all statements that follow the matching case label. The body of
a switch statement is known as a switch block. A statement in the switch block can be
labeled with one or more case or default labels.
In this program, the break statement is used to terminate the flow of matching case statements. If
break statement is not specified, switch statement becomes free flowing and all cases following
matching case including default would be executed.
BREAK STATEMENT
______________________________________________________________________________
Code:
if (intArray[i] == 3)
break;
else
System.out.println(intArray[i]);
______________________________________________________________________________
Output:
BREAK STATEMENT
______________________________________________________________________________
Explanation:
This program shows how to use java break statement to terminate the loop.
The used of break statement is to terminate the loop in between its processing.
Use break statement to come out of the loop instantly. Whenever a break statement is
encountered inside a loop, the control directly comes out of loop and the loop gets
terminated for rest of the iterations. It is used along with if statement, whenever used
inside loop so that the loop gets terminated for a particular condition.
The important point to note here is that when a break statement is used inside a nested
loop, then only the inner loop gets terminated.
It is also used in switch case control. Generally all cases in switch case are followed by a
break statement so that whenever the program control jumps to a case, it doesn’t execute
subsequent cases. As soon as a break is encountered in switch-case block, the control
comes out of the switch-case body.
In this program, the break statement is used to terminate the loop in java. This program breaks
the loop if the array element is equal to true. After break statement is executed, the control goes
to the statement immediately after the loop containing break statement.
IF STATEMENT
______________________________________________________________________________
Code:
booleanblnStatus = true;
if (blnStatus)
System.out.println("Status is true");
______________________________________________________________________________
Output:
IF STATEMENT
______________________________________________________________________________
Explanation:
The Java if statement enables the Java programs to make decisions about what code to execute
depending on the state of variables, or values returned from methods.
The Java if statement is used to test the condition. It checks Boolean condition: true or false.
The types of if statement in java are the following:
if statement
if-else statement
if-else-if ladder
nested if statement
In this program, if statement is used to execute an action if particular condition is true. if() is the
syntax of if statement while is a Boolean expression, and statement is a valid java statement
which will be executed if it’s true. To use multiple statements, enclose them in a block.
IF ELSE STATEMENT
______________________________________________________________________________
Code:
public classSimpleIfElseStatementExample {
inti = 0;
if (i == 0)
System.out.println("i is 0");
else
_____________________________________________________________________________
Output:
IF ELSE STATEMENT
______________________________________________________________________________
Explanation:
The if else statement is used to execute either of two conditions based upon certain condition.
if()
statement1
else
statement2
Code:
inti = 0;
while (i< 5) {
i++;
______________________________________________________________________________
Output:
WHILE LOOP
______________________________________________________________________________
Explanation:
This program shows how to use while loop to iterate in Java program.
The while loop executes a block of code while a boolean expression evaluates to true. It
terminates as soon as the expression evaluates to false. The boolean expression is evaluated
before each iteration.
In this program, the syntax of loop is while()where is Boolean expression. The loop body is
executed as long as the condition is true and it may contain more than one statements. In this
program, it should be enclosed in a block.
The following code will create an infinite loop, since j < 5 will always evaluated to true:
int j = 0;
while(j < 5)
System.out.println("j is : " + j);
DO WHILE LOOP
______________________________________________________________________________
Code:
inti = 0;
do {
i++;
______________________________________________________________________________
Output:
DO WHILE LOOP
______________________________________________________________________________
Explanation:
This program shows how to use do while loop to iterate in Java program.
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to
execute at least one time.
In this program, do while loop executes statement until certain condition become false. The
syntax of do while loop is:
do
while();
where is a Boolean expression
It should not be that the condition is evaluated after executing the loop body. So the loop will be
executed at least once even if the condition is false.
BOOLEAN
______________________________________________________________________________
Code:
boolean b1 = true;
boolean b2 = false;
______________________________________________________________________________
Output:
BOOLEAN
______________________________________________________________________________
Explanation:
This program shows how to declare and use Java primitive boolean variable inside a java class.
A boolean type can have one of two values: true or false. A boolean is used to perform logical
operations, most commonly to determine whether some condition is true.
and switch.
The most common Boolean expressions compare the value of a variable with the value of some
other variable, a constant, or perhaps a simple arithmetic expression. This comparison uses one
In this program, all rational expressions return this type of value. The declare boolean variable is
boolean= ; and the assigned default value is optional.
INT
______________________________________________________________________________
Code:
inti = 0;
int j = 100;
______________________________________________________________________________
Output:
INT
______________________________________________________________________________
Explanation:
This program shows how to declare and use Java primitive intvariable inside a java class.
intare one of the primitive data types supported by Java. Primitive datatypes are predefined by
the language and named by a keyword. The following are the details of int:
In this program, intis 32 bit signed type ranges from –2,147,483,648to 2,147,483,647. int is also
most commonly used integertype in Java.
int = ;
CHAR
______________________________________________________________________________
Code:
______________________________________________________________________________
Output:
CHAR
______________________________________________________________________________
Explanation:
This program shows how to declare and use Java primitive char variable inside a java class.
A char is a single character, that is a letter, a digit, a punctuation mark, a tab, a space or
something similar. A char literal is a single one character enclosed in single quote marks like this
In this program, char is 16 bit type and used to represent Unicode characters. The range of char
is 0 to 65,536. The declare char variable is char = ; and the assigning default value is optional.
DOUBLE
______________________________________________________________________________
Code:
double d = 1232.44;
______________________________________________________________________________
Output:
DOUBLE
______________________________________________________________________________
Explanation:
This program shows how to declare and use Java primitive double variable inside a java class.
The Double class wraps a value of the primitive type double in an object. An object of type
Double contains a single field whose type is double.
In addition, this class provides several methods for converting a double to a String and a String
to a double, as well as other constants and methods useful when dealing with a double.
In this program, double is 64 bit double precision type and used when fractional
precisioncalculation is required.The declaredouble variable is double =; and the assigning
default value is optional.
LONG
______________________________________________________________________________
Code:
importjava.util.*;
______________________________________________________________________________
Output:
LONG
______________________________________________________________________________
Explanation:
This program shows how to declare and use Java primitive long variable inside a java class.
The long data type is a 64-bit two's complement integer. The signed long has a minimum value
of -263 and a maximum value of 263-1. In Java SE 8, the long data type can be use to represent an
unsigned 64-bit long, which has a minimum value of 0 and a maximum value of 2 64-1. Use long
data type when you need a range of values wider than those provided by int. The Long class also
contains methods like compareUnsigned, divideUnsigned etc to support arithmetic operations for
unsigned long.
In this program, long is 64 bit signed type and used when int is not largeenough to hold the
value.The declarelong variable is long =; and the assigning default value is optional.
SHORT
______________________________________________________________________________
Code:
short s1 = 50;
short s2 = 42;
______________________________________________________________________________
Output:
SHORT
______________________________________________________________________________
Explanation:
This program shows how to declare and use Java primitive short variable inside a java class.
The short data type is a 16-bit signed two's complement integer. It has a minimum value of
-32,768 and a maximum value of 32,767 (inclusive). As with byte, the same guidelines apply:
you can use a short to save memory in large arrays, in situations where the memory savings
actually matters.
In this program, short is 16 bit signed type ranges from –32,768 to 32,767. The declare short
variable is short = ; and the assigning default value is optional.
INT TO STRING
______________________________________________________________________________
Code:
inti = 11;
______________________________________________________________________________
Output:
INT TO STRING
______________________________________________________________________________
Explanation:
This int to String java program shows how to convert int to String in Java.
In this program, to convert inttoString, user toString(inti) method of Integer wrapper class.
The Integer class wraps a value of the primitive type int in an object. An object of
type Integer contains a single field whose type is int.
In addition, this class provides several methods for converting an int to a String and a String to
an int, as well as other constants and methods useful when dealing with an int.
STATIC MEMBER VARIABLE
______________________________________________________________________________
Code:
System.out.println(object1.getNumberOfObjects());
System.out.println(object2.getNumberOfObjects());
classObjectCounter {
staticint counter = 0;
publicObjectCounter() {
counter++;
publicintgetNumberOfObjects() {
return counter;
}
STATIC MEMBER VARIABLE
______________________________________________________________________________
Output:
______________________________________________________________________________
Explanation:
This program shows how to declare and use static member variable inside a java class.
Static members are class level variables and shared by all the objectsof the class.To define static
member, use static keyword: static inti=0;.
It should take note that static member variables can be accessed insidenon static methods
because they are class level variables.
The objective counter should increase, since only one variable is shared betweenall objects of
this class, it always return number of objects till now.
FACTORIAL
______________________________________________________________________________
Code:
class Factorial {
inti, fact = 1;
int number = 5;
fact = fact * i;
______________________________________________________________________________
Output:
FACTORIAL
______________________________________________________________________________
Explanation:
There are many ways to write the factorial program in java language. Let's see the 2 ways to
write the factorial program in java.
int number = 5;
LEAP YEAR
______________________________________________________________________________
Code:
else
______________________________________________________________________________
Output:
______________________________________________________________________________
Explanation:
This program shows how to determine whether the given year is leap year or not.
CODE FUNCTION
int year = 2004; year we want to check
if ((year % 400 == 0) || ((year % 4 == 0) && if year is divisible by 4, it is a leap year
(year % 100 != 0)))
LIST EVEN NUMBERS
______________________________________________________________________________
Code:
if (i % 2 == 0) {
______________________________________________________________________________
Output:
______________________________________________________________________________
Example:
This List Even Numbers Java Program shows how to find and list even numbers between 1 and
any given number.
CODE FUNCTION
int limit = 50; define limit
if (i % 2 == 0) { if the number is divisible by 2 then it is even
LIST ODD NUMBERS
______________________________________________________________________________
Code:
if (i % 2 != 0) {
______________________________________________________________________________
Output:
______________________________________________________________________________
Explanation:
This List Odd Numbers Java Program shows how to find and list odd numbers between 1 and
any given number.
CODE FUNCTION
int limit = 50; define the limit
if (i % 2 != 0) { if the number is not divisible by 2 then it is odd
CALCULATE AVERAGE OF ARRAY ELEMENTS
______________________________________________________________________________
Code:
int[] numbers = new int[] { 10, 20, 15, 25, 16, 60, 100 };
int sum = 0;
______________________________________________________________________________
Output:
CALCULATE AVERAGE OF ARRAY ELEMENTS
______________________________________________________________________________
Explanation:
Java provides a data structure, the array, which stores a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often more
useful to think of an array as a collection of variables of the same type.
This program shows how to calculate average value of array elements which is the average value
of array elements would be sum of all elements/total number of elements. Below are the codes
and its function:
CODE FUNCTION
int[] numbers = new int[] { 10, 20, 15, 25, 16, 60, 100 }; define an array
Code:
long startTime;
long endTime;
double time;
startTime = System.currentTimeMillis();
endTime = System.currentTimeMillis();
time = (endTime - startTime) / 1000.0;
}
TIMED COMPUTATION
______________________________________________________________________________
Output:
______________________________________________________________________________
Explanation:
This program performs some mathematical computations and displays theresults. It also displays
the value of the constant Math.PI. It then reports the number of seconds that the computer spent
on this task.
Code Function
long startTime; Starting time of program, in milliseconds.
long endTime; Time when computations are done, in
milliseconds.
double time; Time difference, in seconds.
double width, height, hypotenuse; Sides of a triangle.
ENUM TYPES
______________________________________________________________________________
Code:
enum Month { JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC }
Day tgif;
Month libra;
tgif = Day.FRIDAY;
libra = Month.OCT;
}
ENUM TYPES
______________________________________________________________________________
Output:
______________________________________________________________________________
Explanation:
Code Function
Day tgif; Declare a variable of type Day.
Month libra; Declare a variable of type Month.
tgif = Day.FRIDAY Assign a value of type Day to tgif.
libra = Month.OCT; Assign a value of type Month to libra.
System.out.println(libra); Output value will be: OCT
System.out.println(tgif); Output value will be: FRIDAY
BIRTHDAY PROBLEM
______________________________________________________________________________
Code:
break;
}
used[birthday] = true;
} // end while
System.out.println();
System.out.println("A duplicate birthday was found after "
+ count + " tries.");
}
}
BIRTHDAY PROBLEM
______________________________________________________________________________
Output:
______________________________________________________________________________
Explanation:
This program will simulate choosing people at random and checking the day of the year they
were born on. If the birthday is the same as one that was seen previously, stop, and output the
number of people who were checked.
Code Function
boolean[] used; For recording the possible birthdaysthat have
been seen so far. A valueof true in used[i]
means that a personwhose birthday is the i-th
day of theyear has been found.
Code:
package burger;
import java.util.Scanner;
int bill = 0;
while (ans==1){
System.out.println();
System.out.println();
System.out.println();
System.out.println("Customer What is your order choose number? ");
switch(order)
case 0 :
System.out.println("Burger");
bill = 30;
break;
case 1 :
System.out.println("Cheese Burger");
bill = 50;
break;
case 2 :
System.out.println("Quarter Pounder");
bill = 75;
break;
case 3 :
System.out.println("Hotdog");
bill = 30;
break;
case 4 :
System.out.println("Cheesedog");
bill = 50;
break;
case 5 :
System.out.println("Foot Long");
bill = 75;
break;
case 6 :
System.out.println("Spagz");
bill = 50;
break;
case 7 :
System.out.println("Fries");
bill = 40;
break;
case 8 :
System.out.println("Shake n Rattle");
bill = 30;
break;
case 9:
System.out.println("H20");
bill = 20;
break;
default :
System.out.println("Invalid Input");
System.out.println(total1);
ans = scan.nextInt();
if(ans==2){
break;
System.out.println("Kulangpo!");
}else{
change = money-total1;
}
ORDER TRANSACTION
______________________________________________________________________________
Output:
______________________________________________________________________________
Explanation:
This program will allow the user to order a specific food. The user will just type the order choose
number of the food he/she want. When done inputting the order choose number, the system will
ask the user about the quantity of the food he/she has chosen. The program will multiply the
price of the item and the quantity and ask the user if there’s another order. If there’s no other
order, the program will ask the user about the money he/she have, if there’s change, the program
will compute the amount of his/her change.
PALINDROME
______________________________________________________________________________
Code:
import java.util.Scanner;
word = scan.next();
sb.append(word);
StringBuilderreversesb = sb.reverse();
System.out.println(word);
System.out.println(reverse);
if (word.equals(reverse)) {
System.out.println("Palindrome");
}else{
System.out.println("Not Palindrome");
}
PALINDROME
______________________________________________________________________________
Output:
______________________________________________________________________________
Explanation:
This program will tell if the characters or numbers inputted by the user are still the same even in
reverse order. If it’s still the same then its Palindrome and if not it’s Not Palindrome.
Code Function
StringBuildersb = new StringBuilder(); Creates an empty string builder with a capacity
of 16 (16 empty elements).
StringBuilderreversesb = sb.reverse(); Reverses the sequence of characters in this
string builder.
String reverse = reversesb.toString(); Returns a string that contains the character
sequence in the builder.
System.out.println(word); This will display the word and its reverse
System.out.println(reverse); word.
CALCULATE CIRCLE AREA
______________________________________________________________________________
Source:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
int radius = 0;
try {
radius = Integer.parseInt(br.readLine());
System.exit(0);
} catch (IOExceptionioe) {
System.exit(0);
}
CALCULATE CIRCLE AREA
______________________________________________________________________________
Output:
______________________________________________________________________________
Explanation:
This program will calculate the area of a circle using its radius. The area of a circle is pi * r * r
where r is a radius of a circle. Math.PI constant should be use to get value of pi.
Code Function
BufferedReaderbr = new BufferedReader(new Get the radius from console
InputStreamReader(System.in));
radius = Integer.parseInt(br.readLine());
catch (NumberFormatException ne) { If invalid value was entered
System.out.println("Invalid radius value" + ne);
System.exit(0);
TRY STATEMENT
______________________________________________________________________________
Code:
import java.util.NoSuchElementException;
import java.util.Scanner;
public class TryStatementDemo {
static class TestResource implements AutoCloseable {
static intnextID;
int id;
public TestResource() {
nextID++;
id = nextID;
System.out.println("TestResource object #" +
id + " is being created.");
}
public void close() {
System.out.println("TestResource object #" +
id + " is being closed.");
}
}
public static void main(String[] args) {
System.out.println("This program demonstrates a try..catch statement wtih");
System.out.println("several optional features. Three resources are created");
System.out.println("as part of the try, and they will be closed automatically");
System.out.println("The program will ask you for an integer. Try running the");
System.out.println("program several times with both valid and invalid responses");
System.out.println("to see the flow of control in both the normal and in the");
System.out.println("error case. A lot of extra output is generated to show");
System.out.println("what order things happen in.");
System.out.println();
System.out.println("***Ready to start the try..catch..finally.");
try( Scanner in = new Scanner(System.in);
TestResource one = new TestResource();
TestResource two = new TestResource() ) {
System.out.println("***Starting the try part.");
System.out.print("What's your favorite number? ");
int n = in.nextInt();
System.out.println( (n+1) + " is better!");
System.out.println("***Finishing the try part.");
}
catch (NoSuchElementException e) {
System.out.println("***Starting the catch part.");
System.out.println("Sorry, that's not an integer!");
System.out.println("***Finishing the catch part.");
}
finally {
System.out.println("***In the finally part.");
}
System.out.println("***Done with the entire try..catch..finally.");
}
}
TRY STATEMENT
______________________________________________________________________________
Output:
TRY STATEMENT
______________________________________________________________________________
Explanation:
CODE FUNCTION
int id; Each TestResource object has its own id.
nextID++; Print a message in the constructor so we can
id = nextID; tellwhen the object is created.
System.out.println("TestResource object #" +
id + " is being created.");
System.out.println("TestResource object #" +id Print a message when the object's close()
+ " is being closed."); methodis called, so we can see that that
happens. Note thatthe program never calls
close(). It is called automatically for the
resources that are allocated inthe try statement.
try( Scanner in = new Scanner(System.in); The first three lines of the try includes three
TestResource one = new TestResource(); resource allocations.Each one is a variable
TestResource two = new TestResource() ) { declaration with initialization. Assuming that
System.out.println("***Starting the try part."); the allocation succeeds, the resource will be
System.out.print("What's your favorite closed automatically at the end of the try.
number? "); These resource variables can only be used
int n = in.nextInt(); inthe try part of the statement; they are local to
System.out.println( (n+1) + " is better!"); that block.
System.out.println("***Finishing the try
part.");
catch (NoSuchElementException e) { The catch clause is executed only if a
NoSuchElementException occurs. This
happens if the user's input in not a legal int.
finally { The finally clause is always executed, no
matter what else happens.
DIRECTORY LIST
______________________________________________________________________________
Code:
import java.io.File;
import java.util.Scanner;
String directoryName;
File directory;
String[] files;
Scanner scanner;
if (directory.isDirectory() == false) {
if (directory.exists() == false)
System.out.println("There is no such directory!");
else
System.out.println("That file is not a directory.");
}
else {
files = directory.list();
System.out.println("Files in directory \"" + directory + "\":");
for (int i = 0; i < files.length; i++)
System.out.println(" " + files[i]);
}
}
}
DIRECTORY LIST
______________________________________________________________________________
Output:
______________________________________________________________________________
Explanation:
This program lists the files in a directory specified by the user. The user is asked to type in a
directory name. If the name entered by the user is not a directory, a message is printed and the
program ends.
CODE FUNCTION
String directoryName; Directory name entered by the user.
File directory; File object referring to the directory.
String[] files; Array of file names in the directory.
Scanner scanner; For reading a line of input from the user.
scanner = new Scanner(System.in); Scanner reads from standard input.
COPY FILE
______________________________________________________________________________
Code:
import java.io.*;
String sourceName;
String copyName;
InputStream source;
OutputStream copy;
boolean force;
int byteCount;
try {
source = new FileInputStream(sourceName);
}
catch (FileNotFoundException e) {
System.out.println("Can't find file \"" + sourceName + "\".");
return;
}
try {
copy = new FileOutputStream(copyName);
}
catch (IOException e) {
System.out.println("Can't open output file \"" + copyName + "\".");
return;
}
byteCount = 0;
try {
while (true) {
int data = source.read();
if (data < 0)
break;
copy.write(data);
byteCount++;
}
source.close();
copy.close();
System.out.println("Successfully copied " + byteCount + " bytes.");
}
catch (Exception e) {
System.out.println("Error occurred while copying. "
+ byteCount + " bytes copied.");
System.out.println(e.toString());
}
}
}
COPY FILE
______________________________________________________________________________
Output:
______________________________________________________________________________
Explanation:
This program makes a copy of a file. The original file and the name of the copy must be given as
command-line arguments. In addition, the first command-line argument can be "-f"; if present,
the program will overwrite an existing file; if not, the program will report an error and end if the
output file already exists. The number of bytes that are copied is reported.
CODE FUNCTION
String sourceName; Name of the source file, as specified on the
command line.
String copyName; Name of the copy, as specified on the
command line.
InputStream source; Stream for reading from the source file.
OutputStream copy; Stream for writing the copy.
boolean force; This is set to true if the "-f" option is specified
on the command line.
int byteCount; Number of bytes copied from the source file.
if (args.length == 3 && Get file names from the command line and
args[0].equalsIgnoreCase("-f")) { check for the presence of the -f option. If the
sourceName = args[1]; command line is not one of the two possible
copyName = args[2]; legal forms, print an error message and end this
force = true; program.
}
else if (args.length == 2) {
sourceName = args[0];
copyName = args[1];
force = false;
}
else {
System.out.println( "Usage: java CopyFile
<source-file> <copy-name>");
System.out.println(" or java CopyFile -f
<source-file> <copy-name>");
return;
}
CODE FUNCTION
try { Create the input stream. If an error occurs, end
source = new FileInputStream(sourceName); the program.
}
catch (FileNotFoundException e) {
System.out.println("Can't find file \"" +
sourceName + "\".");
return;
}
File file = new File(copyName); If the output file already exists and the –f
if (file.exists() && force == false) { option was not specified, print an error
System.out.println("Output file exists. Use the message and end the program.
-f option to replace it.");
return;
}
try { Create the output stream. If an error occurs,
copy = new FileOutputStream(copyName); end the program.
}
catch (IOException e) {
System.out.println("Can't open output file \"" +
copyName + "\".");
return;
}
Code:
import java.io.*;
import java.util.Map;
import java.util.TreeMap;
import java.util.Scanner;
TreeMap<String,String> phoneBook;
if ( ! dataFile.exists() ) {
System.out.println("No phone book data file found. A new one");
System.out.println("will be created, if you add any entries.");
System.out.println("File name: " + dataFile.getAbsolutePath());
}
else {
System.out.println("Reading phone book data...");
try( Scanner scanner = new Scanner(dataFile) ) {
while (scanner.hasNextLine()) {
String phoneEntry = scanner.nextLine();
int separatorPosition = phoneEntry.indexOf('%');
if (separatorPosition == -1)
throw new IOException("File is not a phonebook data file.");
name = phoneEntry.substring(0, separatorPosition);
number = phoneEntry.substring(separatorPosition+1);
phoneBook.put(name,number);
}
}
catch (IOException e) {
System.out.println("Error in phone book data file.");
System.out.println("File name: " + dataFile.getAbsolutePath());
System.out.println("This program cannot continue.");
System.exit(1);
}
}
Output:
______________________________________________________________________________
Explanation:
This program lets the user keep a persistent "phone book" that contains names and phone
numbers. The data for the phone book is stored in a file in the user's home directory. The
program is meant only as a demonstration of file use. The phone book data is stored is the form
of Name/Number pairs, with little error checking. In particular, the "phone directory” used in
this program is not even close to what would be needed for a real phone book application.
CODE FUNCTION
private static String DATA_FILE_NAME = The name of the file in which the phone book
".phone_book_demo"; data is kept. The file is stored in the user's
home directory. The "." at the beginning of the
file name means that the file will be a "hidden"
file on Unix-based computers, including Linux
and Mac OS X.
String name, number; Name and number of an entry in the directory
(used at various places in the program).
TreeMap<String,String> phoneBook; Phone directory data structure. Entries are
name/number pairs.
File userHomeDirectory = new Create a dataFile variable of type File to
File( System.getProperty("user.home") ); represent the data file that is stored in the user's
File dataFile = new File( userHomeDirectory, home directory.
DATA_FILE_NAME );
if ( ! dataFile.exists() ) { If the data file already exists, then the data in
System.out.println("No phone book data file the file is read and is used to initialize the
found. A new one"); phone directory. The format of the file must be
System.out.println("will be created, if you add as follows: Each line of the file represents one
any entries."); directory entry, with the name and the number
System.out.println("File name: " + for that entry separated by the character '%'. If
dataFile.getAbsolutePath()); a file exists but does not have this format, then
} the program terminates; this is done to avoid
else { overwriting a file that is being used for another
System.out.println("Reading phone book purpose.
data...");
try( Scanner scanner = new Scanner(dataFile) )
{
while (scanner.hasNextLine()) {
String phoneEntry = scanner.nextLine();
int separatorPosition =
phoneEntry.indexOf('%');
if (separatorPosition == -1)
throw new IOException("File is not a
phonebook data file.");
name = phoneEntry.substring(0,
separatorPosition);
number =
phoneEntry.substring(separatorPosition+1);
phoneBook.put(name,number);
}
}
catch (IOException e) {
System.out.println("Error in phone book data
file.");
System.out.println("File name: " +
dataFile.getAbsolutePath());
System.out.println("This program cannot
continue.");
System.exit(1);
}
}
Scanner in = new Scanner( System.in ); Read commands from the user and carry them
boolean changed = false; // Have any changes out, until the user gives the "Exit from
been made to the directory? program" command.
mainLoop: while (true) {
System.out.println("\nSelect the action that you
want to perform:");
System.out.println(" 1. Look up a phone
number.");
System.out.println(" 2. Add or change a
phone number.");
System.out.println(" 3. Remove an entry
from your phone directory.");
System.out.println(" 4. List the entire phone
directory.");
System.out.println(" 5. Exit from the
program.");
System.out.println("Enter action number (1-5):
");
int command;
if ( in.hasNextInt() ) {
command = in.nextInt();
in.nextLine();
}
else {
System.out.println("\nILLEGAL RESPONSE.
YOU MUST ENTER A NUMBER.");
in.nextLine();
continue;
}
switch(command) {
case 1:
System.out.print("\nEnter the name whose
number you want to look up: ");
name = in.nextLine().trim().toLowerCase();
number = phoneBook.get(name);
if (number == null)
System.out.println("\nSORRY, NO NUMBER
FOUND FOR " + name);
else
System.out.println("\nNUMBER FOR " +
name + ": " + number);
break;
case 2:
System.out.print("\nEnter the name: ");
name = in.nextLine().trim().toLowerCase();
if (name.length() == 0)
System.out.println("\nNAME CANNOT BE
BLANK.");
else if (name.indexOf('%') >= 0)
System.out.println("\nNAME CANNOT
CONTAIN THE CHARACTER \"%\".");
else {
System.out.print("Enter phone number: ");
number = in.nextLine().trim();
if (number.length() == 0)
System.out.println("\nPHONE NUMBER
CANNOT BE BLANK.");
else {
phoneBook.put(name,number);
changed = true;
}
}
break;
case 3:
System.out.print("\nEnter the name whose
entry you want to remove: ");
name = in.nextLine().trim().toLowerCase();
number = phoneBook.get(name);
if (number == null)
System.out.println("\nSORRY, THERE IS NO
ENTRY FOR " + name);
else {
phoneBook.remove(name);
changed = true;
System.out.println("\nDIRECTORY ENTRY
REMOVED FOR " + name);
}
break;
case 4:
System.out.println("\nLIST OF ENTRIES IN
YOUR PHONE BOOK:\n");
for ( Map.Entry<String,String> entry :
phoneBook.entrySet() )
System.out.println(" " + entry.getKey() + ": "
+ entry.getValue() );
break;
case 5:
System.out.println("\nExiting program.");
break mainLoop;
default:
System.out.println("\nILLEGAL ACTION
NUMBER.");
}
}
if (changed) { Before ending the program, write the current
System.out.println("Saving phone directory contents of the phone directory, but only if
changes to file " + some changes have been made to the directory.
dataFile.getAbsolutePath() + " ...");
PrintWriter out;
try {
out = new PrintWriter( new
FileWriter(dataFile) );
}
catch (IOException e) {
System.out.println("ERROR: Can't open data
file for output.");
return;
}
for ( Map.Entry<String,String> entry :
phoneBook.entrySet() )
out.println(entry.getKey() + "%" +
entry.getValue() );
out.flush();
out.close();
if (out.checkError())
System.out.println("ERROR: Some error
occurred while writing data file.");
else
System.out.println("Done.");
SHOW MY NETWORK
______________________________________________________________________________
Code:
import java.net.*;
import java.util.Enumeration;
public class ShowMyNetwork {
public static void main(String[] args) {
Enumeration<NetworkInterface> netInterfaces;
System.out.println();
try {
netInterfaces = NetworkInterface.getNetworkInterfaces();
}
catch (Exception e){
System.out.println();
System.out.println("Sorry, an error occurred while looking for network");
System.out.println("interfaces. The error was:");
System.out.println(e);
return;
}
if (! netInterfaces.hasMoreElements() ) {
System.out.println("No network interfaces found.");
return;
}
while (netInterfaces.hasMoreElements()) {
NetworkInterface net = netInterfaces.nextElement();
String name = net.getName();
System.out.print(" " + name + " : ");
Enumeration<InetAddress> inetAddresses = net.getInetAddresses();
while (inetAddresses.hasMoreElements()) {
InetAddress address = inetAddresses.nextElement();
System.out.print(address + " ");
}
System.out.println();
}
System.out.println();
}
}
SHOW MY NETWORK
______________________________________________________________________________
Output:
______________________________________________________________________________
Explanation:
This short program lists information about available network interfaces on the computer on
which it is run. The name of each interface is output along with a list of one or more IP
addresses for that interface. The names are arbitrary names assigned by the operating system to
the interfaces. The addresses can include both IPv4 and IPv6 addresses. The list should include
the local loopback interface (usually referred to as "localhost") as well as the interface
corresponding to any network card that has been installed and configured.
CALCULATE AREA OF RECTANGLE USING ITS LENGTH AND WIDTH
______________________________________________________________________________
Code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class CalculateRectArea {
public static void main(String[] args) {
int width = 0;
int length = 0;
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter length of a rectangle");
length = Integer.parseInt(br.readLine());
System.out.println("Please enter width of a rectangle");
width = Integer.parseInt(br.readLine());
}
catch (NumberFormatException ne) {
System.out.println("Invalid value" + ne);
System.exit(0);
} catch (IOException ioe) {
System.out.println("IO Error :" + ioe);
System.exit(0);
}
int area = length * width;
System.out.println("Area of a rectangle is " + area);
}
}
CALCULATE AREA OF RECTANGLE USING ITS LENGTH AND WIDTH
______________________________________________________________________________
Output:
______________________________________________________________________________
Explanation:
This program calculates the area of rectangle using its length and width.
CODE FUNCTION
BufferedReader br = new BufferedReader(new Reads the length from console.
InputStreamReader(System.in));
System.out.println("Please enter length of a
rectangle");
length = Integer.parseInt(br.readLine());
System.out.println("Please enter width of a Reads the width from console.
rectangle");
width = Integer.parseInt(br.readLine());
catch (NumberFormatException ne) { If invalid value was entered
System.out.println("Invalid value" + ne);
System.exit(0);
} catch (IOException ioe) {
System.out.println("IO Error :" + ioe);
System.exit(0);
}
int area = length * width; Area of a rectangle is length * width
System.out.println("Area of a rectangle is " +
area);
FIND LARGEST AND SMALLEST NUMBER IN AN ARRAY
______________________________________________________________________________
Code:
int numbers[] = new int[] { 32, 43, 53, 54, 32, 65, 63, 98, 43, 23 };
largetst = numbers[i];
smallest = numbers[i];
}
FIND LARGEST AND SMALLEST NUMBER IN AN ARRAY
______________________________________________________________________________
Output:
______________________________________________________________________________
Explanation:
This program will find the largest and smallest number in an array.
CODE FUNCTION
int numbers[] = new int[] { 32, 43, 53, 54, 32, array of 10 numbers
65, 63, 98, 43, 23 };
int smallest = numbers[0]; assign first element of an array to largest and
int largetst = numbers[0]; smallest
BYTE
______________________________________________________________________________
Code:
byte b1 = 100;
byte b2 = 20;
______________________________________________________________________________
Output:
______________________________________________________________________________
Explanation:
This program shows how to declare and use Java primitive byte variable inside a java class.
byte is smallest Java integer type and has an 8 bit signed type ranges from –128 to 127. byte is
mostly used when dealing with raw data like reading a binary file. Declare byte variable is “byte
= ;”. The assigning default value is optional.
STATIC METHOD
______________________________________________________________________________
Code:
class MathUtility {
______________________________________________________________________________
Output:
______________________________________________________________________________
Explanation:
This program shows how to declare and use static methods inside a java class.
To declare static method use static keyword. Static methods are class level methods and cannot
access any instance member directly. However, it can access members of a particular object
using its reference. Static methods are generally written as a utility method or it performs task for
all objects of the class.
STRING TRIM
______________________________________________________________________________
Code:
______________________________________________________________________________
Output:
______________________________________________________________________________
Explanation:
This program shows how to remove leading and trailing space from string using trim method of
Java String class.
To remove leading and trailing space from string use, public String trim() method of Java String
class.
SUBSTRING
______________________________________________________________________________
Code:
System.out.println(name.substring(6));
System.out.println(name.substring(0, 5));
______________________________________________________________________________
Output:
______________________________________________________________________________
Explanation:
This program describes how substring method of java String class can be used to get substring of
the given java string object.
CODE FUNCTION
System.out.println(name.substring(6)); This will print the substring starting from index
6
System.out.println(name.substring(0, 5)); This will print the substring starting from index
0 upto 4 not 5.
IMPORTANT : Here startIndex is inclusive
while endIndex is exclusive.
CALENDAR
______________________________________________________________________________
Code:
import java.util.Calendar;
______________________________________________________________________________
Output:
______________________________________________________________________________
Explanation:
This example shows how to use Java Calendar class to display current date and time.
CODE FUNCTION
Calendar cal = Calendar.getInstance(); Use getInstance() method to get object of java
Calendar class
Code:
import java.util.ArrayList;
arrayList.add("1");
arrayList.add("2");
arrayList.add("3");
System.out.println(arrayList.get(0));
System.out.println(arrayList.get(1));
System.out.println(arrayList.get(2));
}
______________________________________________________________________________
Output:
______________________________________________________________________________
Explanation:
This program shows how to create an object of Java ArrayList. It also shows how to add
elements to ArrayList and how get the same from ArrayList.
CODE FUNCTION
ArrayList arrayList = new ArrayList(); Create an ArrayList object.
REMOVE ALL ELEMENTS FROM ARRAYLIST
______________________________________________________________________________
Code:
import java.util.ArrayList;
arrayList.add("1");
arrayList.add("2");
arrayList.add("3");
arrayList.clear();
______________________________________________________________________________
Output:
______________________________________________________________________________
Explanation:
This program shows how to remove all elements from java ArrayList object using clear method.
CODE FUNCTION
ArrayList arrayList = new ArrayList(); Create an ArrayList object
arrayList.add("1"); Add elements to Arraylist
arrayList.add("2");
arrayList.add("3");
arrayList.clear(); To remove all elements from the ArrayList use
void clear() method.