0% found this document useful (0 votes)
101 views

Java

The document contains code for a basic "Hello World" Java program. The code defines a class called HelloWorldProgram with a main method that prints "Hello World" to the console. It contains the necessary elements for a simple Java program - a class definition, main method, and call to System.out.println to display output.

Uploaded by

jeremy ramos
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
101 views

Java

The document contains code for a basic "Hello World" Java program. The code defines a class called HelloWorldProgram with a main method that prints "Hello World" to the console. It contains the necessary elements for a simple Java program - a class definition, main method, and call to System.out.println to display output.

Uploaded by

jeremy ramos
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 96

HELLO WORLD PROGRAM

______________________________________________________________________________

Code:

public class HelloWorldProgram {


public static void main(String[] args){
System.out.println("Hello World");
}//End of main
}//End of HelloWorldProgram Class
______________________________________________________________________________

Output:
HELLO WORLD PROGRAM
______________________________________________________________________________

Explanation:

public class HelloWorldProgram {

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.

public static void main(String[] args) {

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.

void: It does not return anything.

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[])
{

Scanner s= new Scanner(System.in);

System.out.println("Enter the radius:");


double r= s.nextDouble();
double area=(22*r*r)/7 ;
System.out.println("Area of Circle is: " + area);
}
}
______________________________________________________________________________

Output:
CALCULATE AREA OF CIRCLE IN A STATIC METHOD
______________________________________________________________________________

Explanation:

As we know that formula in math is :

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 :

public static void main(String args[])


1
( The main function , where the execution of program start from here onwards )

Step -4 :

Scanner s= new Scanner(System.in);


1
( 1.Scanner is class used to scan the input data which was given by user through console.

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 :

1 System.out.println("Enter the radius:");


( above code is giving instructions for user to give the input for radius)

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.

BASIC ARITHMETIC OPERATIONS


______________________________________________________________________________

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

// Perform arithmetic Operations


sum = number1 + number2;
difference = number1 - number2;
product = number1 * number2;
quotient = number1 / number2;
remainder = number1 % number2;

// 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);

++number1; // Increment the value stored in the variable "number1" by 1


// Same as "number1 = number1 + 1"
--number2; // Decrement the value stored in the variable "number2" by 1
// Same as "number2 = number2 - 1"
System.out.println("number1 after increment is " + number1); // Print description and variable
System.out.println("number2 after decrement is " + number2);
quotient = number1 / number2;
System.out.println("The new quotient of " + number1 + " and " + number2
+ " is " + quotient);
}
}

______________________________________________________________________________

Output:

BASIC ARITHMETIC OPERATIONS


______________________________________________________________________________

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.

int number1 = 98;


int number2 = 5;
int sum, difference, product, quotient, remainder;
sum = number1 + number2;
difference = number1 - number2;
product = number1 * number2;
quotient = number1 / number2;
remainder = number1 % number2;

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,

System.out.print("The sum, difference, product, quotient and remainder of ");

System.out.println("sum"); // Print text string "sum" - as it is


System.out.println(sum); // Print the value stored in variable sum, e.g., 98

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.

System.out.println("number1 after increment is " + number1);


System.out.println("number2 after decrement is " + number2);

SUM OF TWO NUMBERS


______________________________________________________________________________

Code:

class Addition {

public static void main(String[] args) {

int a = 5, b = 17, c = 0;

c = a + b;

System.out.println("Sum: " + c);

______________________________________________________________________________

Output:

______________________________________________________________________________

Explanation:

This program has two variables which have already contain values and sum of these numbers
store in third variable.

INCREMENT DECREMENT OPERATOR


______________________________________________________________________________

Code:

public class IncrementDecrementOperatorExample {

public static void main(String[] args) {

inti = 10;

int j = 10;

i++;

j++;

System.out.println("i = " + i);

System.out.println("j = " + j);

int k = i++;

int l = ++j;

System.out.println("k = " + k);

System.out.println("l = " + l);

______________________________________________________________________________

Output:

INCREMENT DECREMENT OPERATOR


______________________________________________________________________________

Explanation:

This program shows how to use Java increment operator (++) and decrement (--) operator.

++ - increment operator increases the operand’s value by one.

-- - decrement operator decreases the operand’s value by one.

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:

public class ModulusOperatorExample {

public static void main(String[] args) {

System.out.println("Java Modulus Operator example");

inti = 50;

double d = 32;

System.out.println("i mod 10 = " + i % 10);

System.out.println("d mod 10 = " + d % 10);

______________________________________________________________________________

Output:

MODULUS OPERATOR
______________________________________________________________________________

Explanation:

This program shows how to use Java modulus operator (%).

Java has important arithmetical operator which is the%. It also known as


the modulus or remainder operator. The % operator returns theremainder of two numbers.

In this program, the modulus operator returns remainder of the division of floating point or
integer types.

SWITCH STATEMENT
______________________________________________________________________________

Code:

public class SwitchStatementExample {

public static void main(String[] args) {

for (inti = 0; i<= 3; i++) {

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:

System.out.println("i is grater than 2");

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.

In this program, the syntax of switch statement is:

switch (i) { switch(expression) {


case 1: case value1:
case 2: case value2:

The expression must be of type int, short, byte or char while the values should be constants
literal values and cannot be duplicated.

The flow of switch statements is:

 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:

public class FreeFlowingSwitchExample {

public static void main(String[] args) {

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:

System.out.println("Free flowing switch example!");

}
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:

public class JavaBreak {

public static void main(String[] args) {

intintArray[] = new int[] { 1, 2, 3, 4, 5 };

System.out.println("Elements less than 3 are : ");

for (inti = 0; i<intArray.length; i++) {

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.

The break statement has the following two usages:

 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:

public class SimpleIfStatementExample {

public static void main(String[] args) {

booleanblnStatus = true;

if (blnStatus)

System.out.println("Status is true");

______________________________________________________________________________

Output:
IF STATEMENT
______________________________________________________________________________

Explanation:

This Java Example shows how to use if statement in Java program.

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 {

public static void main(String[] args) {

inti = 0;

if (i == 0)

System.out.println("i is 0");

else

System.out.println("i is not 0");

_____________________________________________________________________________

Output:
IF ELSE STATEMENT
______________________________________________________________________________

Explanation:

This program shows how to use if else statement in Java program.

The if else statement is used to execute either of two conditions based upon certain condition.

The syntax of if else statement is the following where is a Boolean expression:

if()
statement1
else
statement2

If it’s true, statement1 will be executed, else statement2 will be executed.


WHILE LOOP
______________________________________________________________________________

Code:

public class SimpleWhileLoopExample {

public static void main(String[] args) {

inti = 0;

while (i< 5) {

System.out.println("i is : " + i);

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:

public class DoWhileExample {

public static void main(String[] args) {

inti = 0;

do {

System.out.println("i is : " + i);

i++;

} while (i< 5);

______________________________________________________________________________

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:

public class JavaBoolean {

public static void main(String[] args) {

boolean b1 = true;

boolean b2 = false;

boolean b3 = (10 > 2) ? true : false;

System.out.println("Value of boolean variable b1 is :" + b1);

System.out.println("Value of boolean variable b2 is :" + b2);

System.out.println("Value of boolean variable b3 is :" + b3);

______________________________________________________________________________

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.

A Boolean expression is a Java expression that, when evaluated, returns a Boolean


value: true or false. Boolean expressions are used in conditional statements, such as if, while,

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

of the following relational operators:


Operator Description
== Returns true if the expression on theleft evaluates to the same value as the
expression on theright.
!= Returns true if the expression on theleft does not evaluate to the same value as the
expression on theright.
< Returns true if the expression on theleft evaluates to a value that is less than the
value of theexpression on the right.
<= Returns true if the expression on theleft evaluates to a value that is less than or
equal to theexpression on the right.
> Returns true if the expression on theleft evaluates to a value that is greater than the
value of theexpression on the right.
>= Returns true if the expression on theleft evaluates to a value that is greater than or
equal to theexpression on the right.

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:

public class JavaInt {

public static void main(String[] args) {

inti = 0;

int j = 100;

System.out.println("Value of int variable i is :" + i);

System.out.println("Value of int variable j is :" + j);

______________________________________________________________________________

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:

 Int data type is a 32-bit signed two's complement integer.


 Minimum value is - 2,147,483,648 (-2^31)
 Maximum value is 2,147,483,647(inclusive) (2^31 -1)
 Integer is generally used as the default data type for integral values unless there is a
concern about memory
 The default value is 0
 Example: int a = 100000, int b = -200000

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.

The declare int variable is:

int = ;
CHAR
______________________________________________________________________________

Code:

public class JavaChar {

public static void main(String[] args) {

char ch1 = 'a';

char ch2 = 65; /* ASCII code of 'A'*/

System.out.println("Value of char variable ch1 is :" + ch1);

System.out.println("Value of char variable ch2 is :" + ch2);

______________________________________________________________________________

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:

public class JavaDouble {

public static void main(String[] args) {

double d = 1232.44;

System.out.println("Value of double variable d is :" + d);

______________________________________________________________________________

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.*;

public class JavaLong {

public static void main(String[] args) {

longtimeInMilliseconds = new Date().getTime();

System.out.println("Time in milliseconds is : " + timeInMilliseconds);

______________________________________________________________________________

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:

public class JavaShort {

public static void main(String[] args) {

short s1 = 50;

short s2 = 42;

System.out.println("Value of short variable b1 is :" + s1);

System.out.println("Value of short variable b1 is :" + s2);

______________________________________________________________________________

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:

public class IntToString {

public static void main(String args[]) {

inti = 11;

String str = Integer.toString(i);

System.out.println("int to String : " + i);

______________________________________________________________________________

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:

public class StaticMemberExample {

public static void main(String[] args) {

ObjectCounter object1 = new ObjectCounter();

System.out.println(object1.getNumberOfObjects());

ObjectCounter object2 = new ObjectCounter();

System.out.println(object2.getNumberOfObjects());

classObjectCounter {

staticint counter = 0;

publicObjectCounter() {

counter++;

//returns number of objects created till now

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 {

public static void main(String args[]) {

inti, fact = 1;

int number = 5;

for (i = 1; i<= number; i++) {

fact = fact * i;

System.out.println("Factorial of " + number + " is: " + fact);

______________________________________________________________________________

Output:
FACTORIAL
______________________________________________________________________________

Explanation:

Factorial of n is the product of all positive descending integers. Factorial of n is denoted by


n!.Factorial of n is the product of all positive descending integers.

The factorial is normally used in Combinations and Permutations (mathematics).

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.

o Factorial Program using loop

o Factorial Program using recursion

In this program, the following is the number to calculate factorial:

int number = 5;
LEAP YEAR
______________________________________________________________________________

Code:

public class DetermineLeapYear {

public static void main(String[] args) {

int year = 2004;

if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0)))

System.out.println("Year " + year + " is a leap year");

else

System.out.println("Year " + year + " is not a leap year");

______________________________________________________________________________

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:

public class ListEvenNumbers {

public static void main(String[] args) {

int limit = 50;

System.out.println("Printing Even numbers between 1 and " + limit);

for (inti = 1; i<= limit; i++) {

if (i % 2 == 0) {

System.out.print(i + " ");

______________________________________________________________________________

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:

public class ListOddNumbers {

public static void main(String[] args) {

int limit = 50;

System.out.println("Printing Odd numbers between 1 and " + limit);

for (inti = 1; i<= limit; i++) {

if (i % 2 != 0) {

System.out.print(i + " ");

______________________________________________________________________________

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:

public class CalculateArrayAverage {

public static void main(String[] args) {

int[] numbers = new int[] { 10, 20, 15, 25, 16, 60, 100 };

int sum = 0;

for (inti = 0; i<numbers.length; i++)

sum = sum + numbers[i];

doubleaverage = sum / numbers.length;

System.out.println("Average value of array elements is : " + average);

______________________________________________________________________________

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

int sum = 0; calculate sum of all array elements

double average = sum / numbers.length; calculate average value


TIMED COMPUTATION
______________________________________________________________________________

Code:

public class TimedComputation {

public static void main(String[] args) {

long startTime;
long endTime;
double time;

startTime = System.currentTimeMillis();

double width, height, hypotenuse;


width = 42.0;
height = 17.0;
hypotenuse = Math.sqrt( width*width + height*height );
System.out.print("A triangle with sides 42 and 17 has hypotenuse ");
System.out.println(hypotenuse);

System.out.println("\nMathematically, sin(x)*sin(x) + "


+ "cos(x)*cos(x) - 1 should be 0.");
System.out.println("Let's check this for x = 1:");
System.out.print(" sin(1)*sin(1) + cos(1)*cos(1) - 1 is ");
System.out.println( Math.sin(1)*Math.sin(1)
+ Math.cos(1)*Math.cos(1) - 1 );
System.out.println("(There can be round-off errors when"
+ " computing with real numbers!)");

System.out.print("\nHere is a random number: ");


System.out.println( Math.random() );

System.out.print("\nThe value of Math.PI is ");


System.out.println( Math.PI );

endTime = System.currentTimeMillis();
time = (endTime - startTime) / 1000.0;

System.out.print("\nRun time in seconds was: ");


System.out.println(time);

}
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:

public class EnumDemo {

enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY,


SATURDAY }

enum Month { JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC }

public static void main(String[] args) {

Day tgif;
Month libra;

tgif = Day.FRIDAY;
libra = Month.OCT;

System.out.print("My sign is libra, since I was born in ");


System.out.println(libra);
System.out.print("That's the ");
System.out.print( libra.ordinal() );
System.out.println("-th month of the year.");
System.out.println(" (Counting from 0, of course!)");

System.out.print("Isn't it nice to get to ");


System.out.println(tgif);

System.out.println( tgif + " is the " + tgif.ordinal()


+ "-th day of the week.");
}

}
ENUM TYPES
______________________________________________________________________________

Output:

______________________________________________________________________________

Explanation:

This program demonstrates the use of enum types.

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:

public class BirthdayProblem {


public static void main(String[] args) {
boolean[] used;
int count;
used = new boolean[365];
count = 0;
while (true) {
int birthday;
birthday = (int)(Math.random()*365);
count++;
System.out.printf("Person %d has birthday number %d", count, birthday);
System.out.println();
if ( used[birthday] ) {

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.

int count; The number of people who have been checked.


used = new boolean[365]; Initially, all entries are false.
while (true) { Select a birthday at random, from 0 to 364. If
the birthday has already been used,
quit.Otherwise, record the birthday as used.
int birthday; The selected birthday.
if ( used[birthday] ) { This day was found before; It's a duplicate. We
are done.
ORDER TRANSACTION
______________________________________________________________________________

Code:

package burger;

import java.util.Scanner;

public class Burger {

public static void main(String[] args) {

int total = 0,change,ans=1,total1=0;

int bill = 0;

while (ans==1){

System.out.println("McJollyBidaang Love ko to!");

System.out.println();

System.out.println();

System.out.println("0. burger 30");

System.out.println("1. cheeseburger 50");

System.out.println("2. quarterpounder 75");

System.out.println("3. hotdog 30");

System.out.println("4. cheesedog 50");

System.out.println("5. footlong 75");

System.out.println("6. spagz 50");

System.out.println("7. fries 30");

System.out.println("8. shakenrattle 40");

System.out.println("9. h2o 20");

System.out.println();
System.out.println("Customer What is your order choose number? ");

Scanner scan= new Scanner(System.in);

int order = scan.nextInt();

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("How many items?");

int item = scan.nextInt();


total = bill*item;

total1 = total1 + total;

System.out.println(total1);

System.out.println("ODER AGAIN? press 1 if YES/ 2 if NO");

ans = scan.nextInt();

if(ans==2){

break;

System.out.println("how much money you have ?");

Scanner scan= new Scanner(System.in);

int money = scan.nextInt();

if(money < total1){

System.out.println("Kulangpo!");

}else{

change = money-total1;

System.out.println("Your change is " + change);

}
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;

public class Palindrome {

public static void main(String[] args) {

System.out.println("Enter a letter or a number");

Scanner scan = new Scanner(System.in);

String word = "";

word = scan.next();

StringBuildersb = new StringBuilder();

sb.append(word);

StringBuilderreversesb = sb.reverse();

String reverse = reversesb.toString();

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;

public class CalculateCircleArea {

public static void main(String[] args) {

int radius = 0;

System.out.println("Please enter radius of a circle");

try {

BufferedReaderbr = new BufferedReader(new InputStreamReader(System.in));

radius = Integer.parseInt(br.readLine());

catch (NumberFormatException ne) {

System.out.println("Invalid radius value" + ne);

System.exit(0);

} catch (IOExceptionioe) {

System.out.println("IO Error :" + ioe);

System.exit(0);

double area = Math.PI * radius * radius;

System.out.println("Area of a circle is " + area);

}
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:

This is a program tests a try..catch..finally statement, includingits resource allocation/autoclose


feature.

An object of type TestResource represents a "resource" that canbe automatically closed by a


try..catch statement. For that towork, it has to implement AutoCloseable, which requires it
todefine a close() method. In a try statement with resourceallocation, the close() method will be
called at the end of try, as long as the allocation succeeds.

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;

public class DirectoryList {

public static void main(String[] args) {

String directoryName;
File directory;
String[] files;
Scanner scanner;

scanner = new Scanner(System.in);

System.out.print("Enter a directory name: ");


directoryName = scanner.nextLine().trim();
directory = new File(directoryName);

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.*;

public class CopyFile {

public static void main(String[] args) {

String sourceName;
String copyName;
InputStream source;
OutputStream copy;
boolean force;
int byteCount;

if (args.length == 3 && args[0].equalsIgnoreCase("-f")) {


sourceName = args[1];
copyName = args[2];
force = true;
}
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;
}

try {
source = new FileInputStream(sourceName);
}
catch (FileNotFoundException e) {
System.out.println("Can't find file \"" + sourceName + "\".");
return;
}

File file = new File(copyName);


if (file.exists() && force == false) {
System.out.println(
"Output file exists. Use the -f option to replace it.");
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;
}

byteCount = 0; Copy one byte at a time from the input stream


try { to the output stream, ending when the read()
while (true) { method returns -1 (which is the signal that the
int data = source.read(); end of the stream has been reached). If any
if (data < 0) error occurs, print an error message. Also print
break; a message if the file has been copied
copy.write(data); successfully.
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());
}

PHONE DIRECTORY FILE DEMO


______________________________________________________________________________

Code:

import java.io.*;

import java.util.Map;
import java.util.TreeMap;
import java.util.Scanner;

public class PhoneDirectoryFileDemo {

private static String DATA_FILE_NAME = ".phone_book_demo";

public static void main(String[] args) {

String name, number;

TreeMap<String,String> phoneBook;

phoneBook = new TreeMap<String,String>();

File userHomeDirectory = new File( System.getProperty("user.home") );


File dataFile = new File( userHomeDirectory, DATA_FILE_NAME );

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);
}
}

Scanner in = new Scanner( System.in );


boolean changed = false; // Have any changes been made to the directory?

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) {
System.out.println("Saving phone directory changes to file " +
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.");
}
}
}
______________________________________________________________________________

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;
}

System.out.println("Network interfaces found on this computer:");

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:

public class FindLargestSmallestNumber {

public static void main(String[] args) {

int numbers[] = new int[] { 32, 43, 53, 54, 32, 65, 63, 98, 43, 23 };

int smallest = numbers[0];

int largetst = numbers[0];

for (int i = 1; i < numbers.length; i++) {

if (numbers[i] > largetst)

largetst = numbers[i];

else if (numbers[i] < smallest)

smallest = numbers[i];

System.out.println("Largest Number is : " + largetst);

System.out.println("Smallest Number is : " + smallest);

}
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:

public class JavaByte {

public static void main(String[] args) {

byte b1 = 100;

byte b2 = 20;

System.out.println("Value of byte variable b1 is :" + b1);

System.out.println("Value of byte variable b1 is :" + b2);

______________________________________________________________________________

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:

public class StaticMethodExample {

public static void main(String[] args) {

int result = MathUtility.add(1, 2);

System.out.println("(1+2) is : " + result);

class MathUtility {

public static int add(int first, int second) {

return first + second;

______________________________________________________________________________

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:

public class RemoveLeadingTrailingSpace {

public static void main(String[] args) {

String str = " String Trim Example ";

String strTrimmed = str.trim();

System.out.println("Original String is: " + str);

System.out.println("Removed Leading and trailing space");

System.out.println("New String is: " + strTrimmed);

______________________________________________________________________________

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:

public class JavaSubstringExample {

public static void main(String args[]) {

String name = "Hello World";

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;

public class JavaSimpleCalendarExample {

public static void main(String[] args) {

Calendar cal = Calendar.getInstance();

System.out.println("Today is : " + cal.getTime());

______________________________________________________________________________

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

System.out.println("Today is : " + Use getTime() method of Calendar class to get


cal.getTime()); date and time
ARRAYLIST
______________________________________________________________________________

Code:

import java.util.ArrayList;

public class SimpleArrayListExample {

public static void main(String[] args) {

ArrayList arrayList = new ArrayList();

arrayList.add("1");

arrayList.add("2");

arrayList.add("3");

System.out.println("Getting elements of ArrayList");

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;

public class RemoveAllElementsOfArrayListExample {

public static void main(String[] args) {

ArrayList arrayList = new ArrayList();

arrayList.add("1");

arrayList.add("2");

arrayList.add("3");

System.out.println("Size of ArrayList before removing elements : " + arrayList.size());

arrayList.clear();

System.out.println("Size of ArrayList after removing elements : " + arrayList.size());

______________________________________________________________________________

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.

You might also like