Java is a cross-platform language originally developed by James Gosling at Sun Microsystems. It enables writing programs for many operating systems using a C/C++-like syntax but with a simpler object model and fewer low-level facilities. Java programs are compiled to bytecode that can run on any Java Virtual Machine (JVM) regardless of computer architecture. Common Java development tools include Eclipse and NetBeans integrated development environments.
2. History of Java programming
• A programming language originally developed by James Gosling at Sun
Microsystems .
• Java is a cross-platform language that enables you to write programs for many
different operating systems
• syntax : C and C++ but has a simplerobject model and fewer lowlevel facilities .
• Oak=>Green=>Java
• Java enables users to develop and deploy applications on the Internet for servers,
desktop computers, and small hand-held devices, applications on the server side,
Web server to generate dynamic Web pages
10. 1. multiline comment: /* and end with */.
2. single-line comment or end-of-line comment : // I hate java
3. documentation comment: /** and ends with */
Comment
11. Test1public class Test1{
public static void main(String[] args)
{
/* For */
System.out.println("Computer Bactouk Center");
}
}
Ex2:
public class Welcome4
{
// main method begins execution of Java application
public static void main( String args[] )
{
System.out.printf( "%sn%sn", "Welcome to", "Java Programming!" );
} // end method main
} // end class Welcome4
12. public(access specifier) class Test1(identifier)
{
public static void main(String[] args)
{
System.out.println("Computer Bactouk Center");
}
}
public means that it is accessible by any other classes
static means that it is unique.
void is the return value but void means nothing which means there will be no return
value .
main is the name of the method
(String[] args) is used for command line parameters.
Curly brackets are used again to group the contents of main together .
static allows main( ) to be called without having to instantiate a particular instance of
the class
Methods are able to perform tasks and return information
A string is sometimes called a character string, a message or a string literal.
System.out is known as the standard output object.
“Computer Backtouk Center” is argument.
Class block
Method
block
13. import java.util.*;
public class TestJava {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int a;
a=sc.nextInt();
System.out.println(a);
}
}
Note: sc.nextDouble(), sc.next()
• import declaration that helps the compiler locate a class that is used in this program.
Reading Input from the Console
14. Step1: Compiler
• The javac compiler creates a file called
Example.class(C:>javac Example.java)
• Program is run, the following output is
displayed()(C:>java Example)
15. Variables
• Variables are used to store values to be used later in a program. They are called
variables because their values can be changed.
• Variables are for representing data of a certain type. To use a variable, you declare
it by telling
• the compiler its name as well as what type of data it can store. The variable
declaration tells
• the compiler to allocate appropriate memory space for the variable based on its
data type.
• The variable is the basic unit of storage, combination of an identifier, a type, and an
optional initializer.
• type identifier [ = value][, identifier [= value] ...] ;
– int a, b, c;
– int d = 3, e, f = 5;
– byte z;
– z = 22;
– double d = 3.14159;
– char x = 'x'; //’x’ is initialize constant
16. Named Constants
• The value of a variable may change during the execution of a program, but a named
constant or simply constant represents permanent data that never changes.
– final datatype CONSTANTNAME = VALUE;
public class ComputeArea
{
public static void main(String[] args)
{
final double PI; // Declare a constant
PI=100;
// Assign a radius
double radius = 20;
// Compute area
double area = radius * radius * PI;
// Display results
System.out.println("The area for the circle of radius " + radius + " is " + area);
}
}
20. Integer
public class DayTime
{
public static void main(String[] args)
{
int point1;
int point2;
point1=10;
point2=200;
int day=30;
System.out.println("From " + point1 + "km to " + point2 + "km is " +
(point2-point1) + "km");
System.out.println("From " + point1 + " to " + point2 + "km, we take " + day + "
days");
}
}
21. Char
• Char in java is 0 to 65,536
• Char in C is 0 to 127(Not IBM computer)
• Char in C is 0 to 255(IBM computer)
public class TestA
{
public static void main(String[] args)
{
char ch1='A';
char ch2=97;
System.out.println("ch1=" + ch1 + "nch2=" + ch2);
}
}
22. Character Escape
- Suppose you want to print a message with quotation marks in the output. Can you
write a statement like this?
23. Floating-point numbers
public class Area
{
public static void main(String[] args)
{
double pi, r, a;
r = 21.2;
pi = 3.1416;
a = pi * r * r;
System.out.println("Area of circle is " + a);
}
}
24. Floating-point numbers
public class Calc
{
public static void main(String[] args)
{
float v1=6;
float v2=4.3f;
System.out.println(v1 + "+" + v2 + "=" + (v1+v2));
System.out.println(v1 + "-" + v2 + "=" + (v1-v2));
System.out.println(v1 + "*" + v2 + "=" + (v1*v2));
System.out.println(v1 + "/" + v2 + "=" + (v1/v2));
System.out.println(v1 + "%" + v2 + "=" + (v1%v2));
}
}
• Floating-point literals are written with a decimal point. By default, a floating-point literal is
treated as a double type value. For example, 5.0 is considered a double value, not a float value.
You can make a number a float by appending the letter f or F, and you can make a number a
double by appending the letter d or D. For example, you can use 100.2f or 100.2F for a float
number, and 100.2d or 100.2D for a double number
25. boolean
• True/false
public class Area
{
public static void main(String[] args)
{
boolean sleep=true; sleep=false;
System.out.printf("I am so tired so feel seep("
+ sleep + ")");
}
}
27. Note: Java Strings
• To represent a string of characters, use the data type called String.
• objects designed to represent a sequence of characters.
• In Java, ordinary strings are objects of the class String.
• A string literal is a sequence of characters between double quotes.
– String s=new String();
• S=“sdfsdf”
– String s=new String(“Texto”);
– String s=“texto”;
• String s=“texto”
• s=s + “libre”
• If one of the operands is a nonstring (e.g., a number), the nonstring value is
converted into a string and concatenated with the other string.
• EX:
– String message = "Welcome " + "to " + "Java";
– String s = "Chapter" + 2; // s becomes Chapter2
– String s1 = "Supplement" + 'B'; // s1 becomes SupplementB
• Method: next() and nextLine()?
• == check to see if the two string are exactly the same object
• .equals() // . equalsIgnoreCase() method check if the two strings have the same
value;
30. Equality and relational operators
• Tertiary Operator
Result=(condition)?TrueReturn:FalseReturn;
31.
32. Dynamic Initialization
public class TestA
{
public static void main(String[] args)
{
double x=100.0;
double result=Math.sqrt(x);
System.out.println("result sqrt(x)=" + result);
}
}
33. The Scope and Lifetime of Variables
public class TestA
{
public static void main(String args[])
{
int x; // known to all code within main
x = 10;
if(x == 10)
{ // start new scope
in y = 20; // known only to this block
// and y both known here.
System.out.println("x and y: " + x + " " + y);
x = y * 2;
}
// y = 100; // Error! y not known here
// x is still known here.
int y=30;
System.out.println("x is " + x);
System.out.println("y is " + y);
}
}
34. The Scope and Lifetime of Variables
public class TestA
{
public static void main(String args[])
{
int x;
for(x = 0; x < 3; x++)
{
int y = -1; // y is initialized each time block is entered
System.out.println("y is: " + y); // this always prints -1
y = 100;
System.out.println("y is now: " + y);
}
}
}
35. Type Conversion and Casting
• narrowing conversion
– if you want to assign an int value to a byte variable? This
conversion will not be performed automatically, because a
byte is smaller than an int.
– Explicit cast statement: v1=(type)v2;
• Automatic Conversions
– int type is always large enough to hold all valid byte
values, so no explicit cast statement .
byte a = 40;
byte b = 50;
byte c = 100;
int d = a * b / c;
36. narrowing conversion
• int a; byte b; b = (byte) a;
• Casting Incompatible Types
public class JavaTest {
public static void main(String[] args)
{
int a;
byte b;
a=10;
b = (byte)a;
System.out.println(b);
a=10;
b=(byte)a;
System.out.println(b);
}
}
37. narrowing conversion
public class JavaTest {
public static void main(String[] args)
{
byte b;
int i = 257;
double d = 323.142;
System.out.println("nConversion of int to byte.");
b = (byte) i;
System.out.println("i and b " + i + " " + b);
System.out.println("nConversion of double to int.");
i = (int) d;
System.out.println("d and i " + d + " " + i);
System.out.println("nConversion of double to byte.");
b = (byte) d;
System.out.println("d and b " + d + " " + b);
}
}
38. Automatic Conversions
public class JavaTest
{
public static void main(String[] args)
{
double b;
int i = 257;
double d = 323.142;
System.out.println("nConversion of int to byte.");
b = i;
System.out.println("i and b " + i + " " + b);
System.out.println("nConversion of double to int.");
i = (int) d;
System.out.println("d and i " + d + " " + i);
System.out.println("nConversion of double to byte.");
b = d;
System.out.println("d and b " + d + " " + b);
}
}
39. Formatting Console Output
• to format the output using the printf method.
– System.out.printf(format, item1, item2, ..., itemk)
* (int)(Math.random() *10)
returns a random single-digit integer (i.e., a
number between 0 and 9)
40. import java.util.Scanner;
public class SubtractionQuiz {
public static void main(String[] args) {
int number1 = (int)(Math.random() * 10);
int number2 = (int)(Math.random() * 10);
{
int temp = number1;
number1 = number2;
number2 = temp;
}
System.out.print ("What is " + number1 + " - " + number2 + "? ");
Scanner input = new Scanner(System.in);
System.out.println("You are correct!");
else
System.out.println("Your answer is wrongn" + number1 + " - “ +
number2 + " should be " + (number1 - number2));
}}
42. Array
• An array is a special kind of object that contains values called
elements. The java array enables the user to store the values of the
same type in contiguous memory allocations.
• One-Dimensional Arrays
– a list of like-typed variables
– Step:
• Declaration : type array-var[ ];
• Allocate : array-var = new type[size];
• Assign value: array_var[n]=value;
– Or step
• Declaration and Allocate: type arr-var[]=new type[size];
• Assign value: array-var[n]=values;
– Or step
• Declaration + Allocate + Assign: type arr-var[]={v1,v2,v3…vn};
• Note: array_var.length
43. One-Dimensional Arrays
public class JavaTest
{
public static void main(String[] args)
{
String arr_Day[];
arr_Day=new String[7];//or Sring arr_Day=new String[7];
arr_Day[0]="Monday";
arr_Day[1]="Tuesday";
arr_Day[2]="Wednesday";
arr_Day[3]="Thursday";
arr_Day[4]="Friday";
arr_Day[5]="Saturday";
arr_Day[6]="Sunday";
System.out.println("Today is " + arr_Day[5]);
}
}
44. One-Dimensional Arrays
public class TestJava
{
public static void main(String args[])
{
int month_days[];
month_days = new int[12];
month_days[0] = 31;
month_days[1] = 28;
month_days[2] = 31;
month_days[3] = 30;
month_days[4] = 31;
month_days[5] = 30;
month_days[6] = 31;
month_days[7] = 31;
month_days[8] = 30;
month_days[9] = 31;
month_days[10] = 30;
month_days[11] = 31;
System.out.println("April has " + month_days[3] + " days.");
}
}
Copy Array:
int[] sourceArray = {2, 3, 1, 5, 10};
int[] targetArray = new int[sourceArray.length];
for (int i = 0; i < sourceArray.length; i++)
{
targetArray[i] = sourceArray[i];
}
45. Passing array to Method
public static void printArray(int[] array){
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}}
printArray(new int[]{3, 1, 2, 6, 4, 2});
//===============
public static void main(String[] args) {
int x = 1; // x represents an int value
int[] y = new int[10]; // y represents an array of int values
//y[0]=100;
m(x, y); // Invoke m with arguments x and y
System.out.println("x is " + x);
System.out.println("y[0] is " + y[0]);
}
public static void m(int number, int[] numbers) {
number = 1001; // Assign a new value to number
numbers[0] = 5555; // Assign a new value to numbers[0]
}
46.
47. Return array From Method
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
for (int i = 0, j = result.length - 1;i < list.length; i++, j--) {
result[j] = list[i];
}
return result;
}
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
48. Multidimensional Arrays(Two Diemensional)
• are actually arrays of arrays
• two-dimensional array to store a matrix
– elementType arrayRefVar[][] = new elementType[nR][nC];
– elementType[][] arrayRefVar;
• arrayRefVar = new elementType[nR][nC];
– elementType arrayRefVar[][];
• arrayRefVar = new elementType[nR][nC];
– elementType[][] arrayRefVar = {{….},{….},….,{…}}
– arrayRefVar.length => Length of row
– arrayRefVar[index].length => Length of column
EX:
• for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
int i1 = (int)(Math.random() * matrix.length);
int j1 = (int)(Math.random() * matrix[i].length);
// Swap matrix[i][j] with matrix[i1][j1]
int temp = matrix[i][j];
matrix[i][j] = matrix[i1][j1];
matrix[i1][j1] = temp;
}}
52. Passing Two-Dimensional Arrays to Methods
• System.out.println("nSum of all elements is " + sum(m));
• public static int sum(int[][] m) {
int total = 0;
for (int row = 0; row < m.length; row++) {
for (int column = 0; column < m[row].length; column++) {
total += m[row][column];
}}
return total;}
53. Control Statements
• To cause the flow of execution to advance and
branch based on changes to the state of a
program.
– selection: allow your program to choose different
paths of execution based upon the outcome of an
expression or the state of a variable.
– Iteration: enable program execution to repeat one
or more statements
– jump: allow your program to execute in a
nonlinear fashion
54. Conditional Operator
• Ternary operator because it has three terms.
– test ? trueresult : falseresult
– Int smaller;
– smaller = x < y ? x : y;
56. Select statement
• If: be used to route program execution through two different
paths.
if (condition) statement1;
else statement2;
Ex:
int a=7, b=8;
if(a < b) a = 0;
else b = 0;
58. Nested if
if(i == 10)
{
if(j < 20) a = b;
If(k > 100) c = d; // this if is
else a = c; // associated with this else
}
else a = d; // this else refers to if(i == 10)
62. switch
• Provides easy way to dispatch execution to different parts of code
based on the value of an expression.
switch (expression)
{
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
.
.
.
case valueN:
// statement sequence
break;
default:
// default statement sequence
}
• The switch-expression must yield a value of char, byte, short, or int type and must
always be enclosed in parentheses.
• The value1, and valueN must have the same data type as the value of the switch-
expression. Note that value1, and valueN are constant expressions, meaning that
they cannot contain variables, such as 1 + x.
• char ch=(char)st.charAt(0);
63. class SampleSwitch
{
public static void main(String args[])
{
for(int i=0; i<6; i++)
switch(i) {
case 0:
System.out.println("i is zero.");
Break;
case 1:
System.out.println("i is one.");
break;
case 2:
System.out.println("i is two.");
Break;
case 3:
System.out.println("i is three.");
break;
default:
System.out.println("i is greater than 3.");
}
}}
64. class MissingBreak {
public static void main(String args[]) {
for(int i=0; i<12; i++)
switch(i) {
case 0:
case 1:
case 2:
case 3:
case 4:
System.out.println("i is less than 5");
break;
case 5:
case 6:
case 7:
case 8:
case 9:
System.out.println("i is less than 10");
break;
default:
System.out.println("i is 10 or more");
}
}
}
65. Nested switch Statements
switch(count) {
case 1:
switch(target) {
case 0:
System.out.println("target is zero");break;
case 1:
System.out.println("target is one");break;
}
break;
case 2: // ...
66. Switch or if?
• The switch differs from the if in that switch can only test
for equality, whereas if can evaluate any type of
Boolean expression. That is, the switch looks only for a
match between the value of the expression and one of
its case constants.
• No two case constants in the same switch can have
identical values. Of course, aswitch statement and an
enclosing outer switch can have case constants in
common.
• Aswitch statement is usually more efficient than a set of
nested ifs.
67. Iteration Statements
• for, while, and do-while called loop
• loop that controls how many times an operation or a
sequence of operations is performed in succession.
• A loop repeatedly executes the same set of
instructions until a termination condition is met.
68. While
while(condition)
{
// body of loop
}
Ex:
class While
{
public static void main(String args[])
{
int n = 10;
while(n >= 0)
{
System.out.println("tick " + n);
n--;//n=n-1
}
}
}
69. int a = 10, b = 20;
while(a > b)
System.out.println("This will not be displayed");
final int NUMBER_OF_QUESTIONS = 5;
long startTime = System.currentTimeMillis();
int number1 = (int)(Math.random() * 10);
70. import java.util.*;
public class TestJava{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
double min,n;
System.out.print("Please Enter value:");min=sc.nextDouble();
while(sc.hasNextDouble())
{
n=sc.nextDouble();
if(min>n)
min=n;
System.out.println("Min=" + min);
}
}
}
71. do-while
do
{
body of loop
} while (condition);
Ex:
class DoWhile {
public static void main(String args[]) {
int n = 10;
do {
System.out.println("tick " + n);
n=n-2;
} while(n > 0);
}
}
- import java.io.*;
- String.substring(BeginIndex,
EndIndex)
- String.charAt(pos)
75. class ForTick
{
public static void main(String args[]) {
for(int n=10; n>0; n--)
System.out.println("tick " + n);
}
}
76. class Comma {
public static void main(String args[]) {
int a, b;
for(a=1, b=4; a<b && a<c; a++, b--) {
System.out.println("a = " + a);
System.out.println("b = " + b);
}}}
Ex:
class ForVar {
public static void main(String args[]) {
int i;
boolean done = false;
i = 0;
for( ; !done; ) {
System.out.println("i is " + i);
if(i == 10) done = true;
i++;
}}}
77. The For-Each Version of the for Loop
• for(type itr-var : collection) statement-block
class ForEach {
public static void main(String args[]) {
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
// use for-each style for to display and sum the values
for(int x : nums) {
System.out.println("Value is: " + x);
sum += x;
}
System.out.println("Summation: " + sum);
}
}
78. class ForEach2 {
public static void main(String args[]) {
int sum = 0;
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// use for to display and sum the values
for(int x : nums)
{
System.out.println("Value is: " + x);
sum += x;
if(x == 5) break; // stop the loop when 5 is obtained
}
System.out.println("Summation of first 5 elements: " + sum);
}
}
79. class ForEach3 {
public static void main(String args[]) {
int sum = 0;
int nums[][] = new int[3][5];
// give nums some values
for(int i = 0; i < 3; i++)
for(int j=0; j < 5; j++)
nums[i][j] = (i+1)*(j+1);
// use for-each for to display and sum the values
for(int x[] : nums) {
for(int y : x) {
System.out.println("Value is: " + y);
sum += y;
}
}
System.out.println("Summation: " + sum);
}
}
80. class Search {
public static void main(String args[]) {
int nums[] = { 6, 8, 3, 7, 5, 6, 1, 4 };
int val = 5;
boolean found = false;
// use for-each style for to search nums for val
for(int x : nums) {
if(x == val) {
found = true;
break;
}
}
if(found)
System.out.println("Value found!");
}
}
81. Using break
class BreakLoop {
public static void main(String args[]) {
for(int i=0; i<100; i++) {
if(i == 10) break; // terminate loop if i is 10
System.out.println("i: " + i);
}
System.out.println("Loop complete.");
}
}
82. class BreakLoop3 {
public static void main(String args[]) {
for(int i=0; i<3; i++) {
System.out.print("Pass " + i + ": ");
for(int j=0; j<100; j++) {
if(j == 10) break; // terminate loop if j is 10
System.out.print(j + " ");
}
System.out.println();
}
System.out.println("Loops complete.");
}
}
83. Using break as a civilized form of goto.
class Break {
public static void main(String args[]) {
boolean t = true;
first: {
aaaa: {
third: {
System.out.println("Before the break.");
if(t) break first; // break out of second block
System.out.println("This won't execute");
}
System.out.println("This won't execute");
}
System.out.println("This is after second block.");
}
}
}
84. Using continue
class Continue {
public static void main(String args[]) {
for(int i=0; i<10; i++) {
System.out.print(i + " ");
if (i%2 == 0) continue;
System.out.println("");
}
}
}
85. return
class Return {
public static void main(String args[]) {
boolean t = true;
System.out.println("Before the return.");
if(t) return; // return to caller
System.out.println("This won't execute.");
}
}
89. The Math class contains the methods
• Math.pow(3.5, 2.5) returns 22.91765
• Math.sqrt(4) returns 2.0
• Math.ceil(-2.1) returns -2.0
• Math.floor(2.1) returns 2.0
• Math.max(2.5, 3) returns 3.0
• Math.min(2.5, 3.6) returns 2.5
• Math.abs(-2) returns 2
90. Function/Method in java
• We can do so by defining a method. The method is for creating reusable code.
• Methods are referred to as procedures and functions. A value-returning
method is called a function; a void method is called a procedure.
•
Public class TestJava{
function1body
public static void main(String[] args)
{
function1caller;
function2caller;
}
function2body
}
• The syntax :
modifier returnValueType methodName(list of parameters) {
// Method body;}
91. A value-returning method
• public static float functionName([parameter..])
{
statementblock;
return value;
}
A void method
• public static void functionName([parameter..])
{
statementblock;
}
94. import java.util.*;
public class TestJava{
public static void sum(float x, float y)
{
System.out.println(x+ "" + y + "=" + result);
}
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
float x,y,result;
System.out.print("Enter x=");x=sc.nextFloat();
System.out.print("Enter y=");y=sc.nextFloat();
sum(x,y);
}
}
95. Passing Primitive data type Method Argument by Value:
• The arguments must match the parameters in order, number, and compatible type, as
defined in the method signature.
• Compatible type means that you can pass an argument to a parameter without explicit
casting, such as passing an int value argument to a double value parameter.
• public static void nPrintln(String message, int n) {
for (int i = 0; i < n; i++)
System.out.println(message);
}
Passing Primitive data type Method Argument by Reference: NONE
• To generalize the foregoing discussion, a random character between any two characters
ch1 and ch2 with ch1 < ch2 can be generated as follows:
• (char)(ch1 + Math.random() * (ch2 – ch1 + 1))
’d’ – ’k’
(char)(’d’ + Math.random()*(’k’-’d’+1));
Overloading Methods
• another method with the same name but different parameters.
Reading Input from the Console
- Java uses System.out to refer to the standard output device
- System.in to the standard input device.
EX:
import java.util.Scanner; // Scanner is in the java.util package
public class ComputeAreaWithConsoleInput {
public static void main(String[] args) {
// Create a Scanner object
Scanner input = new Scanner(System.in);//
// Prompt the user to enter a radius
System.out.print("Enter a number for radius: ");
double radius = ;
// Compute area
double area = radius * radius * 3.14159;
// Display result
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}
Identifiers
Names of things that appear in the program. Such names are called
identifiers. All identifiers must obey the following rules:
■ An identifier is a sequence of characters that consists of letters, digits, underscores
(_), and dollar signs ($).
■ An identifier must start with a letter, an underscore (_), or a dollar sign ($). It cannot
start with a digit.
■ An identifier cannot be a reserved word. (See Appendix A, “Java Keywords,” for a
list of reserved words.)
■ An identifier cannot be true, false, or null.
■ An identifier can be of any length.
There are three benefits of using constants:
(1) you don’t have to repeatedly type the same value;
(2) if you have to change the constant value (e.g., from 3.14 to 3.14159 for PI), you need to
change it only in a single location in the source code;
(3) a descriptive name for a constant makes
the program easy to read.
public class ShowCurrentTime {
public static void main(String[] args) {
// Obtain the total milliseconds since midnight, Jan 1, 1970
long totalMilliseconds = System.currentTimeMillis();
// Obtain the total seconds since midnight, Jan 1, 1970
long totalSeconds = totalMilliseconds / 1000;
// Compute the current second in the minute in the hour
long currentSecond = (int)(totalSeconds % 60);
// Obtain the total minutes
long totalMinutes = totalSeconds / 60;
// Compute the current minute in the hour
long currentMinute = totalMinutes % 60;
// Obtain the total hours
long totalHours = totalMinutes / 60;
// Compute the current hour
long currentHour = totalHours % 24;
// Display results
System.out.println("Current time is " + currentHour + ":" + currentMinute + ":" + currentSecond + " GMT");
}
}
* int i = 10; Same effect as int newNum = 10 * i++; int newNum = 10 * i;i = i + 1;
* int i = 10; Same effect as int newNum = 10 * (++i); i = i + 1;int newNum = 10 * i;
import java.util.Scanner;
public class Test4{
public static void main(String[] args)
{
System.out.print("Enter you play:");
Scanner sc=new Scanner(System.in);
int answer=sc.nextInt();
if(answer>=1 && answer<=4)
{
int number=(int)(Math.random()*3+1);
if(answer==number)
{
System.out.println("Your answer = result");
}
else
{
System.out.printf("The result is %d but you put %d\n",number,answer);
System.out.println("Your answer # result");
}
}
else
{
System.out.println("Out of range 1-4");
}
}
}
import java.util.Random;
public class j1 {
public static void main(String[] args) {
int[] myList=new int[10];
Random rand=new Random();
for(int i=0;i<10;i++)
{
myList[i]= rand.nextInt(10);
}
for(int i=0;i<10;i++)
{
System.out.println(myList[i]);
}
//sum
int sum=0;
for(int i=0;i<10;i++)
{
sum=sum+myList[i];
}
//max
int max=myList[0];
for(int i=0;i<10;i++)
{
if(myList[i]>max) max=myList[i];
}
//min
int min=myList[0];
for(int i=0;i<10;i++)
{
if(myList[i]<min) min=myList[i];
}
System.out.println("sum=" + sum);
System.out.println("max=" + max);
System.out.println("min=" + min);
}
}
public class Test5 {
public static void main(String[] args) {
int n=3;
java.util.Scanner sc1=new java.util.Scanner(System.in);
System.out.print("Enter number of names:");
n=sc1.nextInt();
java.util.Scanner sc=new java.util.Scanner(System.in);
String[] name=new String[n];
//insert
for(int i=0;i<n;i++)
{
System.out.print("Enter name:");
name[i]=sc.nextLine();
}
//search
java.util.Scanner sc2=new java.util.Scanner(System.in);
System.out.print("Enter text to search:");
String search=new String();
search=sc2.nextLine();
boolean b=false;
int j=0;
for(int i=0;i<name.length;i++)
{
if(search.equalsIgnoreCase(name[i]))
{
b=true;
j++;
}
}
if(b==false)
{
System.out.println("Not Found!");
}
else
{
System.out.println("Found:" + j + " time");
}
//update
java.util.Scanner sc3=new java.util.Scanner(System.in);
System.out.print("Enter text to to Update:");
String update=new String();
update=sc3.nextLine();
boolean b1=false;
int j1=0;
for(int i=0;i<name.length;i++)
{
if(search.equalsIgnoreCase(name[i]))
{
b1=true;
name[i]=update;
j1++;
}
}
if(b1==false)
{
System.out.println("Not Found!");
}
else
{
System.out.println("Update :" + j1 + " time");
}
//delete
java.util.Scanner sc4=new java.util.Scanner(System.in);
System.out.print("Enter text to to DELETE:");
String delete=new String();
delete=sc4.nextLine();
boolean b2=false;
int j2=0;
for(int i=0;i<name.length;i++)
{
if(delete.equalsIgnoreCase(name[i]))
{
b2=true;
name[i]="";
j2++;
}
}
if(b2==false)
{
System.out.println("Not Found!");
}
else
{
System.out.println("Update :" + j2 + " time");
}
//output
for(int i=0;i<n;i++)
{
System.out.println("Enter name:" + name[i]);
}
}
}
import java.util.Scanner;
public class Test4 {
public static void main(String[] args) {
String set1 =
" 1 3 5 7\n" +
" 9 11 13 15\n" +
"17 19 21 23\n" +
"25 27 29 31";
String set2 =
" 2 3 6 7\n" +
"10 11 14 15\n" +
"18 19 22 23\n" +
"26 27 30 31";
String set3 =
" 4 5 6 7\n" +
"12 13 14 15\n" +
"20 21 22 23\n" +
"28 29 30 31";
String set4 =
" 8 9 10 11\n" +
"12 13 14 15\n" +
"24 25 26 27\n" +
"28 29 30 31";
String set5 =
"16 17 18 19\n" +
"20 21 22 23\n" +
"24 25 26 27\n" +
"28 29 30 31";
// Create a Scanner
Scanner input = new Scanner(System.in);
// Prompt the user to answer questions
System.out.print("Is your birthday in Set1?\n");
System.out.print(set1);
System.out.print("\nEnter 0 for No and 1 for Yes: ");
int answer = input.nextInt();
int day=0;
if (answer == 1)
day += 1;
System.out.print("\nIs your birthday in Set2?\n" );
System.out.print(set2);
System.out.print("\nEnter 0 for No and 1 for Yes: ");
answer = input.nextInt();
if (answer == 1)
day += 2;
System.out.print("Is your birthday in Set3?\n");
System.out.print(set3);
System.out.print("\nEnter 0 for No and 1 for Yes: ");
answer = input.nextInt();
if (answer == 1)
day += 4;
System.out.print("\nIs your birthday in Set4?\n");
System.out.print(set4);
System.out.print("\nEnter 0 for No and 1 for Yes: ");
answer = input.nextInt();
if (answer == 1)
day += 8;
System.out.print("\nIs your birthday in Set5?\n");
System.out.print(set5);
System.out.print("\nEnter 0 for No and 1 for Yes: ");
answer = input.nextInt();
if (answer == 1)
day += 16;
System.out.println("\nYour birthday is " + day + "!");
}
}
/**
* @(#)Test2.java
*
* Test2 application
*
* @author
* @version 1.00 2013/9/14
*/
import java.util.Date;
import java.util.Scanner;
public class Test2 {
public static void main(String[] args) {
System.out.println("Answer the question here:");
String answer="";
char ch='n';
int v1=0,v2=0;
Scanner sc=new Scanner(System.in);
int i=0;
while(ch!='y' && ch!='Y')
{
Date d=new Date();
System.out.println("You start at :" + d.getHours()+ ":" + d.getMinutes() + ":" + d.getSeconds() );
while(i<5)
{
v1=(int)(Math.random()*10);
v2=(int)(Math.random()*10);
if(v1<v2)
{
int v;
v=v1;
v1=v2;
v2=v;
}
System.out.print(v1 + "-" + v2 + "=");
int ans=sc.nextInt();
if(v1-v2!=ans)
{
answer+=(i+1) + ", False ";
}
else
{
answer+=(i+1) + ",True ";
}
i++;
}
System.out.println(answer);
Date d1=new Date();
System.out.println("You finished at :" + d1.getHours()+ ":" + d1.getMinutes() + ":" + d1.getSeconds() );
System.out.print("Do you wnat to close(y/n)?");
ch=sc.next().charAt(0);
i=0;
answer="";
}
}
}
import java.util.Scanner;
import java.io.*;
public class Test1 {
public static void main(String[] args) {
char ch='n';
Scanner sc=new Scanner(System.in);
String fullName=new String("");
String firstName="";
String lastName="";
do
{
int i=0;
System.out.printf("Enter full Name:");
fullName=sc.nextLine();
do{
if(fullName.charAt(i)==' ')
{
firstName=fullName.substring(0,i);
lastName=fullName.substring(i+1);
break;
}
i++;
}while(i<fullName.length()-1);
System.out.printf("First Name is %s\n",firstName);
System.out.printf("Last Name is %s\n",lastName);
System.out.print("Do you want to close(y/n)?:");
ch=(char)(sc.next().charAt(0));
}while(ch!='y' && ch!='Y');
}
}
import java.util.Scanner;
class Test11 {
public static void main(String args[]){
// Print random characters between 'a' and 'z', 25 chars per line
for (int i = 0; i < 'z'-'a'; i++)
{
char ch =(char)('a' + Math.random() * ('z' - 'a' + 1));
if(i%5==0 && i!=0)
{
System.out.println();
System.out.print(ch);
}
else
{
System.out.print(ch);
}
}
}
}