[go: up one dir, main page]

0% found this document useful (0 votes)
44 views14 pages

Javac Yourname - Java Java Yourname Rules: - : Java Convention 1 (Name of Classes) Java Convention 2 (Naming of Variables)

The document describes the steps to write and run a Java program. It begins by installing the JDK, then writing code in a text editor and saving it as a .java file. The code is then compiled to a .class file using javac and executed using java. It provides conventions for naming classes and variables and good practices like commenting and indenting code.

Uploaded by

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

Javac Yourname - Java Java Yourname Rules: - : Java Convention 1 (Name of Classes) Java Convention 2 (Naming of Variables)

The document describes the steps to write and run a Java program. It begins by installing the JDK, then writing code in a text editor and saving it as a .java file. The code is then compiled to a .class file using javac and executed using java. It provides conventions for naming classes and variables and good practices like commenting and indenting code.

Uploaded by

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

0.

install the JDK and set the system


Step 1: Coding (edit)
saves the code in a file FileName.java (on the secondary storage unit).

Step 2: Compile
translates the code into bytecode and stores it in a new file FileName.class (on the secondary storage unit).

Step 3: Class loader


reads the .class file (and loads it into the primary storage unit).

Step 4: Bytecode verifier


checks that the bytecodes are valid

Step 5: Execution on Java Virtual Machine (JVM)


The JVM reads the bytecode and just-in-time (JIT) compiles them (can store data values in the primary
memory during execution).

We then have to follow these steps:


1. Write the code in the text editor and save the file as YourName.java
2. Open the command prompt (under Windows) and navigate to the directory where the .java file is stored
3. Run the compiler1: javac YourName.java. The compiler creates the file YourName.class and stores it in the
same directory.
4. Execute the program using: java YourName

Rules:
-one class can be defined by file!
-A projects need at least one class with a method called 'main'.

Java convention 1 (Name of classes)


Start each word in the name of a class with an upper-case letter: HelloWorld.java
Java convention 2 (Naming of variables)
Variable names should always start with a lower case letter (as opposed to classes) and every following
word in the name should start with a upper case letter:
Good examples: age, yearsOfEducation, labourIncome

Good practice 1 (Comments)


Start every file with a comment describing the purpose of the code.
Good practice 2 (Indent)
Indent the whole code by level: every time you open a new brace, make sure the foll. block-code is
indented.
Good practice 3 (Names of variables)
Use self-explaining names for variables which describe what the content of the variable is about.

/*
*/

public class HelloWorld{ // DEFINE THE ACTUAL CLASS


// Main method begins the execution of the Java program
public static void main(String[] args){ // DECLARE A METHOD (We can add as many methods as we want)
The whole code of this method should be written within the curly braces.
System.out.println("Hello World"); //THE ACTUAL 'ALGORITHM' (command, each statement (instruction) must be ended
with a semi-colon)

} // end of the method main


} // end class HelloWorld
Display information on the screen
The class System.out has several methods to print information

Command: System.out.print("Hello World")

print is a method of the subclass out of the class System.


The dots (.) are used to access a sub-element of another (attribute or methods).

print() is a method (function), where the all arguments of the method are written within the parentheses.
This method has a single argument of type string.

Methods can have several arguments, which are then separated by commas (,). At the end of each
statement (typically a line) we have to add a semi-colon (;).
F.
Class: System.out
Method Description
println() Prints the text on a line and then adds a line break
printf(String, args) Allows you to print formatted text. For example:
1 int age = 29;
2 System.out.printf("The age is: %s years",age);

\n
\t Horizontal tab
\\ Is used to print a single backslash (\)
\" Is used to print a quotation marks
%s Print the value of another argument [only printf()]) as is.
Supports virtually any type of data (text, numbers, etc)
%6.3f Prints a numeric value in a specific format: 6 digits before and 3 digits after the comma are presented
1 System.out.printf("%9.6f",123.12345678); // prints 123.123457
3 System.out.printf("%9.0f",123.12345678); // prints 123

abstract finally public


boolean float return
break for short
byte goto static
case if strictfp
catch implements super
char import switch
class instanceof synchronized
const int this
continue interface throw
default long throws
do native transient
double new try
else package void
extends private volatile
final protected while

data types: primitive types


Category Type Range/values Memory
Integers byte Range [-128,127] 8 Bits
short Range [-32768,32767] 16 Bits
int Range [_231,231 _ 1] 32 Bits
long Range [_263,263 _ 1] 64 Bits
Floating point float approx. _3.4028E+38 32 Bits
double approx _1.7977E+308 64 Bits
Booleans boolean TRUE / FALSE n/a
Text char Unicode symbols n/a
String* Unicode symbols > char

Declaring and initialising variables:


1 int
age = 29; // Declare variable 'age' and set value of 29
2 int
year; // Declares variable 'year', sets value to zero.
3 double income = 2563.65; // declares and initialised 'income' with the value of 2563.65
5
6 boolean female = TRUE; // declares the boolean variable 'female' and sets the value to TRUE;
7 char name = "Laura"; // Declares and initalised 'name' with the value 'Laura'

Changing the values of variables when they are already declared

Definition 1 (Declare a variable/object)


Declaring a variable or objects is creating the variable and reserving/allocating the memory required.
Declaring does not automatically initialise the variable.
1 int age; // Declares 'age', but does not initialise it.
2 boolean female; //Declares 'female', but does not initialise it.
A variable can only be declared once!

Definition 2 (Initialise a variable)


Initialising a variable is when we attribute a values to a variable. We can initialise a variable upon declaration
by directly setting the value.
1 age=20; // Initialises the previously declared variable.
2 boolean female=TRUE; // Declares and initialised 'female' with the value TRUE

Prompt user input (very basic version)


to receive information from the user.

import java.util.Scanner; \\ import the subclass Scanner of the class util


public class Addition {

public static void main(String[] args) {


Scanner input = new Scanner(System.in); \\ initialise one instance of the class Scanner and name it input.

System.out.print("Enter the first number: ");


int number1 = input.nextInt(); \\use the Scanner to prompt a value from the user. nextInt() indicates expect integer
System.out.print("Enter the second number: ");
int number2 = input.nextInt();
int sum = number1 + number2;
System.out.printf("The sum is: %s\n",sum);
}
}

Warning 1 (Wrong/unexpected user input)


Programmers have generally a user-behaviour in mind when they program an algorithm. It is therefore
import to try to anticipate wrong and unexpected user inputs and to deal with them.

Warning 2 (Division of two integers yields an integer!)


When dividing an integer (int) by another integer (int) Java returns an integer:
5 //To obtain a double, we have to cast the numerator to a double:
6 double w = (double)x/y; // Returns 2.5 stored in a double!
Warning 3 (Dropping curly braces is dangerous)
Only the first line after the if-clause is conditional:
1 if(N>0)
2 mean = sum / N;
3 ssq = sumsq / N;
is equal to
1 if(N>0){
2 mean = sum / N;
3}
4 ssq = sumsq / N; //which is not what we had in mind! There is a risk of a division by zero!
Warning 4 (Dropping curly braces is dangerous)
If you forget to change the condition within the while-loop, the loop will continue forever!
This is not a compilation error, thus most likely the IDE will not warn you about it!

Basic arithmetic operations


Java operation Symbol Algebraic expression Java expression
Remainder % r mod s r%s

Compound Assignment Operators


Assignment operator Code example Operation
+= a += b a = a+b
-= a -= b a = a-b
*= a *= b a = a*b
/= a /= b a = a/b
%= a %= b a = a%b

Increment and decrement operators


a++; ++a; --a; a--;

Advanced mathematical functions


Additional methods can/must be imported before we can use them. For example, the class java.Math is a
collection of mathematical functions. It includes (among others):

abs() absolute value max(a,b) maximum value


ceil() ceiling min(a,b) minimum value
cos() cosine random() random value (0-1)
exp() exponential round() round to integer
floor() oor sqrt() squared root
log() natural logarithm pow(a,b) power:ab
log10() logarithm base 10
F.
To access any method of the class Math, we have to write first the name of the class, then a dot (.), followed
by the name of the method: for example abs().
1 public class MathExample {
2 public static void main(String[] args){
3 double x = 4;
4 double a = Math.abs(-x); // a=4
6 double c = Math.min(4, 9); // c = 4
7 double d = Math.pow(4, 3); // d = 4^3 = 64
8 double e = Math.sqrt(x); // e = 2
9}
10 }
Control statements
We might want to have parts of the code to be executed only under some circumstances.
if-elseif-else,switch: mutually exclusive options
while, do, for: loops, repeating the same code several times

The general logic of these statements is:


statement(condition){
code
}
F.
Control statements: relational operators
Java expressions:
== , != , > , >= <=

Control statements: if-else


After the word if we open parentheses to put all the conditions in it. Once the parentheses closed, we open
curly braces and put all the code within the braces.
1 public static void getMax(double a, double b){
2 if(a > b){
3 System.out.println("a is bigger than b");
4 }
5 else if (a==b){
6 System.out.println("a is equally big as b");
7 }
8 else{
9 System.out.println("a is smaller than b");
10 }
11 }

The use of else and else if is optional. We can also limit the code to a simple if clause:
1 if(engery==0){
2 System.out.println("I have no more energy");
3}

Control statements: switch


In case of having several discrete options, it can be better to use switch rather than if with many if-else:
1 switch(i){
2 case 1: System.out.println("Monday"); break;
3 case 2: System.out.println("Tuesday"); break;
;
8 case 7: System.out.println("Sunday"); break;
9 default: System.out.println("Oops, something went wrong");
10 }
-works only with discrete choices for byte, short, char, and int
-default is added to capture all other (wrong) values that could be entered: example of error handling.
-The code between case X: and break; can be longer, even multiple lines.

Control statements: while-loop


The while loop executes as long as the condition is satisfied. while-loops are extremely useful, when you
don't know the exact number of iterations needed (for instance in a numerical optimisation).
1 inti=1; // set the runner to 1
2 while(i<10){ // execute as long as the runner is below 10
3 System.out.println(i);
4 i++; // increment the runner by one unit
5}

Control statements: for-loop


In case you know how many times you want to execute the loop (the end of the loop is known), the for-loop
might be better.
1 for(int i=1;i<10;i++){
2 System.out.println(i);;
3}
Notes:
The firrst argument initialises the runner variable (cannot be an already initialised variable)
The second argument is the condition when to stop
The third argument is the increment of the runner

The increment can be fancier than just adding one unit:


1 for(int i=2;i<=64;i*=2 ){
2 System.out.print(i+" ");
3}

Control statements: do-while-loop


The do-while-loop is similar to the while loop but the condition is verified only after each iteration.
1 int i=1;
2 do{
3 System.out.println(i);
4 i++;
5 }while(i<10);
Control statements: break and continue
For all the loops we have seen, we can also use break and continue.
break Stops the execution of the current loop, even if the general condition for stopping is not yet achieved.
continue Skip the remaining code for the current iterations and continues with the next iteration.
1 for(int i=1;i<10;i++){
2 if(i==5)
3 continue;
4 if(i==8)
5 break;
6 System.out.print(i+" ");
7}

random
public static double random()
Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.
Returned values are chosen pseudorandomly with (approximately) uniform distribution from
that range.

When this method is first called, it creates a single new pseudorandom-number generator,
exactly as if by the expression

new java.util.Random()
This new pseudorandom-number generator is used thereafter for all calls to this method and is
used nowhere else.

This method is properly synchronized to allow correct use by more than one thread. However,
if many threads need to generate pseudorandom numbers at a great rate, it may reduce
contention for each thread to have its own pseudorandom-number generator.

Returns:
a pseudorandom double greater than or equal to 0.0 and less
than 1.0.
See Also:
Random.nextDouble()

nextDouble

public double nextDouble()


Returns the next pseudorandom, uniformly distributed double value
between 0.0 and 1.0 from this random number generator's sequence.

The general contract of nextDouble is that one double value, chosen (approximately)
uniformly from the range 0.0d (inclusive) to 1.0d (exclusive), is pseudorandomly generated
and returned.

The method nextDouble is implemented by class Random as if by:


public double nextDouble() {

return (((long)next(26) << 27) + next(27))

/ (double)(1L << 53);


}

The hedge "approximately" is used in the foregoing description only because the next method
is only approximately an unbiased source of independently chosen bits. If it were a perfect
source of randomly chosen bits, then the algorithm shown would choose double values from
the stated range with perfect uniformity.

[In early versions of Java, the result was incorrectly calculated as:

return (((long)next(27) << 27) + next(27))


/ (double)(1L << 54);
This might seem to be equivalent, if not better, but in fact it introduced a large nonuniformity
because of the bias in the rounding of floating-point numbers: it was three times as likely that
the low-order bit of the significand would be 0 than that it would be 1! This nonuniformity
probably doesn't matter much in practice, but we strive for perfection.]
Returns:
the next pseudorandom, uniformly distributed double value
between 0.0 and 1.0 from this random number generator's sequence

import java.util.Random;

/** Generate 10 random integers in the range 0..99. */


public final class RandomInteger {

public static final void main(String... aArgs){


log("Generating 10 random integers in range 0..99.");

//note a single Random object is reused here


Random randomGenerator = new Random();
for (int idx = 1; idx <= 10; ++idx){
int randomInt = randomGenerator.nextInt(100);
log("Generated : " + randomInt);
}

log("Done.");
}

private static void log(String aMessage){


System.out.println(aMessage);
}
}

import java.util.Random;

/** Generate random integers in a certain range. */


public final class RandomRange {
public static final void main(String... aArgs){
log("Generating random integers in the range 1..10.");

int START = 1;
int END = 10;
Random random = new Random();
for (int idx = 1; idx <= 10; ++idx){
showRandomInteger(START, END, random);
}

log("Done.");
}

private static void showRandomInteger(int aStart, int aEnd, Random


aRandom){
if (aStart > aEnd) {
throw new IllegalArgumentException("Start cannot exceed End.");
}
//get the range, casting to long to avoid overflow problems
long range = (long)aEnd - (long)aStart + 1;
// compute a fraction of the range, 0 <= frac < range
long fraction = (long)(range * aRandom.nextDouble());
int randomNumber = (int)(fraction + aStart);
log("Generated : " + randomNumber);
}

private static void log(String aMessage){


System.out.println(aMessage);
}
}

public final class RandomGaussian {

public static void main(String... aArgs){


RandomGaussian gaussian = new RandomGaussian();
double MEAN = 100.0f;
double VARIANCE = 5.0f;
for (int idx = 1; idx <= 10; ++idx){
log("Generated : " + gaussian.getGaussian(MEAN, VARIANCE));
}
}

private Random fRandom = new Random();

private double getGaussian(double aMean, double aVariance){


return aMean + fRandom.nextGaussian() * aVariance;
}

private static void log(Object aMsg){


System.out.println(String.valueOf(aMsg));
}
}

Solution 1:
randomNum = minimum + (int)(Math.random() * maximum);
Problem:
randomNum can be bigger than maximum.
Solution 2:
Random rn = new Random();
int n = maximum - minimum + 1;
int i = rn.nextInt() % n;
randomNum = minimum + i;

In Java 1.7 or later, the standard way to do this is as follows:


import java.util.concurrent.ThreadLocalRandom;

// nextInt is normally exclusive of the top value,


// so add 1 to make it inclusive
int randomNum = ThreadLocalRandom.current().nextInt(min, max + 1);
See the relevant JavaDoc. This approach has the advantage of not needing to
explicitly initialize a java.util.Random instance, which can be a source of confusion and
error if used inappropriately.
However, conversely there is no way to explicitly set the seed so it can be difficult to
reproduce results in situations where that is useful such as testing or saving game
states or similar. In those situations, the pre-Java 1.7 technique shown below can be
used.

Use:

Random ran = new Random();


int x = ran.nextInt(6) + 5;
The integer x is now the random number that has a possible outcome of 5-10.

minimum + rn.nextInt(maxValue - minvalue + 1)

You can edit your second code example to:

Random rn = new Random();


int range = maximum - minimum + 1;
int randomNum = rn.nextInt(range) + minimum;

Just a small modification of your first solution would suffice.

Random rand = new Random();


randomNum = minimum + rand.nextInt((maximum - minimum) + 1);

If you want to test it out try something like this.

Random rn = new Random();

for(int i =0; i < 100; i++)


{
int answer = rn.nextInt(10) + 1;
System.out.println(answer);
}
public static String promptForCarType(){
Scanner input = new Scanner(System.in);
char type;
System.out.println("(E) Economy - 50 TL");
System.out.println("(M) Midsize - 70 TL");
System.out.println("(F) Fullsize - 100 TL");
do{
System.out.println("Enter the car type (E/M/F) : ");
type = input.next().charAt(0);
type = Character.toUpperCase(type);
} while (type != 'E' && type != 'M' && type != 'F' ); //I tried to
define condition with "||" operator,didn't work.

switch(type) {
case 'E' : ;return "Economy";
case 'M' : return "Midsize";
case 'F' : return "Fullsize";
default : return " ";

public static String promptForCarType() {


Scanner input = new Scanner(System.in);
char type;
for (;;) {
System.out.println("(E) Economy - 50 TL");
System.out.println("(M) Midsize - 70 TL");
System.out.println("(F) Fullsize - 100 TL");
System.out.println("Enter the car type (E/M/F) : ");
type = input.next().charAt(0);
type = Character.toUpperCase(type);
switch (type) {
case 'E':
return "Economy";
case 'M':
return "Midsize";
case 'F':
return "Fullsize";
}
}
}

A simple example to illustrate how java.util.Scanner works would be reading a single


integer from System.in. It's really quite simple.
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();next
To retrieve a username I would probably use sc.nextLine().
System.out.println("Enter your username: ");
Scanner scanner = new Scanner(System.in);
String username = scanner.nextLine();
System.out.println("Your username is " + username);

public static void printX()


{
System.out.print("X");
}

public static void printCars(String name, int num)


{
System.out.print(name);
for(int i=0; i < num; i++)
{
printX();
}
System.out.println();
}

If you want to have it available outside the for, you have to declare it in a scope that is
active in the location you want to access it; e.g. just outside the for loop:
int i;
for (i = 0; i < 1000; ++ i)
;
// i is accessible in this scope
System.out.println(i);
Alternatively, if it is more appropriate, you could declare a separate variable and store
the value of interest in it:

int k = ...;
for (int i = 0; i < 1000; ++ i)
if (condition) // for example
k = i;
// k is accessible in this scope, i is not
System.out.println(k);
import java.util.Scanner;
public class Timing {

public static void main(String[] args) {


Scanner input = new Scanner(System.in);
// Display a message to the user and instruct him/her what to do.
System.out.print("Please indicate your time zone as compared to
UTC.\n");
System.out.print("For example:\n\t if you are living in Central
Europe (UTC+1), indicate 1.\n");
System.out.print("\t if you are living in Mexico (UTC-6), indicate
-6\n");
System.out.print("Your input:");

int diff = input.nextInt(); // Cast the input to an integer

long totalMilliseconds = System.currentTimeMillis();


long seconds = totalMilliseconds / 1000 % 60;
long minutes = totalMilliseconds / 1000 / 60 % 60;
long hours = totalMilliseconds / 1000 / 60 / 60 % 24;

// Adapt the hours


hours +=diff; // Adding the difference to match the time zone
if(hours<0){ // Ensure that we don't have negative values (happens
when one day behind UTC)
hours+=24;
}
else if(hours>24){ // Ensure that we don't have values >24 (happens
when one day ahead of UTC)
hours-=24;
}

// In order to nicely display the time zone, we distinguish the


output for positive and negative values
if(diff>=0){
System.out.printf("The time in the selected time zone
(UTC+%s) is: %s:%s:%s \n",diff,hours,minutes,seconds);
}
else{
System.out.printf("The time in the selected time zone (UTC%s)
is: %s:%s:%s \n",diff,hours,minutes,seconds);
}

}
public class Time {

public static void main(String[] args) {


long totalMilliseconds = System.currentTimeMillis();
totalMilliseconds -=1000*60*60*6;
long seconds = totalMilliseconds / 1000 % 60;
long minutes = totalMilliseconds / 1000 / 60 % 60;
long hours = totalMilliseconds / 1000 / 60 / 60 % 24;

System.out.printf("It is %s:%s:%s (Mexico City


Time)\n",hours,minutes,seconds);

You might also like