Home Random Page



Type “javac”. Is it working?


Java History. Introduction to Simple Java Program

Java (programming language) Java is a programming language originally developed by James Gosling at Sun Microsystems (which has since merged into Oracle Corporation) and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities. Java applications are typically compiled to bytecode (class file) that can run on any Java Virtual Machine (JVM) regardless of computer architecture. Java is a general-purpose, concurrent, class-based, object-oriented language that is specifically designed to have as few implementation dependencies as possible. It is intended to let application developers "write once, run anywhere", meaning that code that runs on one platform does not need to be edited to run on another. Java is currently one of the most popular programming languages in use, particularly for client-server web applications, with a reported 10 million users.Microprocessors are having a profound impact in intelligent consumer-electronic devices. Recognizing this, Sun Microsystems in 1991 funded an internal corporate research project code-named Green, which resulted in the development of a C++ - based language that its creator, James Gosling, called Oak after an oak tree outside his window at Sun. It was later discovered that there already was a computer language called Oak. When a group of Sun people visited a local coffee shop, the name Java was suggested, and it stuck.

Installing the Java Development Kit on Windows: Java is a programming language that allows programs to be written that can then be run on more than one type of operating system. A program written in Java can run on Windows, UNIX, Linux etc. as long as there is a Java runtime environment installed. In order to develop our own program we need some library JDK and JRE.

1. Download JDK and JRE. (http://www.oracle.com/technetwork/java/javase/downloads/index.html)

Install. Be sure that installation finished successfully.

Change class path. Open Computer > Properties> Advanced > Environment Variables > Create

4. Enter to Variable name “PATH” and Variable value “java_directory” . Like “C:\Program Files\Java\jdk7.1.0_22\bin”

Click OK.

Open command line (cmd)

Type “javac”. Is it working?

It will look like:



Creating Your First Application Your first application, HelloWorldAppication, will simply display the greeting "Hello world!". To create this program, you will:

· Create a source fileA source file contains code, written in the Java programming language, that you and other programmers can understand. You can use any text editor to create and edit source files.

· Compile the source file into a “.class" fileThe Java programming language compiler (javac) takes your source file and translates its text into instructions that the Java virtual machine can understand. The instructions contained within this file are known as bytecodes.

· Run the programThe Java application uses the Java virtual machine to run your application.

Create a Source File To create a source file, you have two options:

· You can save the file HelloWorldApp.java on your computer and avoid a lot of typing. Then, you can go straight to Compile the Source File into a .class File.

· Or, you can use the following (longer) instructions.

First, start your editor. You can launch the Notepad editor from the Start menu by selecting Programs > Accessories > Notepad. In a new document, type in the following code:

class HelloWorldApp { public static void main(String[] args) { System.out.println("Hello World!"); }}Be Careful When You Type Note: Type all code, commands, and file names exactly as shown. Both the compiler (javac) and launcher (java) are case-sensitive, so you must capitalize consistently.
HelloWorldApp is not the same as helloworldapp.

Save the code in a file with the name HelloWorldApp.java. To do this in Notepad, first choose the File > Save As menu item. Then, in the Save As dialog box:

  1. Using the Save in combo box, specify the folder (directory) where you'll save your file. In this example, the directory is java on the C drive.
  2. In the File name text field, type "HelloWorldApp.java", including the quotation marks.
  3. From the Save as type combo box, choose Text Documents (*.txt).
  4. In the Encoding combo box, leave the encoding as ANSI.

When you're finished, the dialog box should look like this.

The Save As dialog just before you click Save.

Now click Save, and exit Notepad.

Compile the Source File into a .class File Bring up a shell, or "command," window. You can do this from the Start menu by choosing Command Prompt (Windows XP), or by choosing Run... and then entering cmd. The shell window should look similar to the following figure.

A shell window.

The prompt shows your current directory. When you bring up the prompt, your current directory is usually your home directory for Windows XP (as shown in the preceding figure.

To compile your source file, change your current directory to the directory where your file is located. For example, if your source directory is java on the C drive, type the following command at the prompt and press Enter:

cd C:\java

Now the prompt should change to C:\java>. Note: To change to a directory on a different drive, you must type an extra command: the name of the drive. For example, to change to the java directory on the D drive, you must enter D:, as shown in the following figure.

Changing directory on an alternate drive.

If you enter dir at the prompt, you should see your source file, as the following figure shows.

Directory listing showing the .java source file.

Now you are ready to compile. At the prompt, type the following command and press Enter.

javac HelloWorldApp.java

The compiler has generated a bytecode file, HelloWorldApp.class. At the prompt, type dir to see the new file that was generated, as shown in the following figure.

Directory listing, showing the generated .class file

Now that you have a .class file, you can run your program.

If you encounter problems with the instructions in this step, consult the Common Problems (and Their Solutions).

Run the Program

In the same directory, enter the following command at the prompt:

java HelloWorldApp

The next figure shows what you should now see:

The program prints "Hello World!" to the screen.

Congratulations! Your program works!




Variables and the Primitive Types


Programs manipulate data that are stored in memory. In machine language, data can only

be referred to by giving the numerical address of the location in memory where it is stored.

In a high-level language such as Java, names are used instead of numbers to refer to data. It

is the job of the computer to keep track of where in memory the data is actually stored; the

programmer only has to remember the name. A name used in this way — to refer to data stored

in memory — is called a variable.

In Java, the only way to get data into a variable—that is, into the box that the variable

names—is with an assignment statement . An assignment statement takes the form:

{ variable } = { expression } ;

where { expression } represents anything that refers to or computes a data value.

The Primitive Types and String:

There are eight so-called primitive types built into Java. The primitive types are named :

byte, short, int, long, float, double, char, and boolean. The first four types hold integers

(whole numbers such as 7, -38477, and 0). The four integer types are distinguished by the

ranges of integers they can hold. The float and double types hold real numbers (such as 3.6 and

-145.99). Again, the two real types are distinguished by their range and accuracy. A variable

of type char holds a single character from the Unicode character set. And a variable of type

boolean holds one of the two logical values trueorfalse.

1. A variable of type byte holds a string of eight bits, which can represent any of the integers between -128 and 127, inclusive.

byte b = 1204;

2. A variable of type short corresponds to two bytes (16 bits). Type short have values in

the range -32768 to 32767.

short s = 100;

3. A variable of type int corresponds to four bytes (32 bits). Type int have values in

the range -2147483648 to 2147483647.

int i = 20;

4. A variable of type long corresponds to eight bytes (64 bits). Type long have values in

the range -9223372036854775808 to 9223372036854775807.

long l = 1L;

5. A variable of type float data type is represented in four bytes of memory, using a standard method for encoding real numbers. The maximum value for a float is about 10 raised to the power 38.

float f = 2f;

6. A double takes up 8 bytes, can range up to about 10 to the power 308.

double d = 3.14;

7. A variable of type char occupies two bytes in memory. The value of a char variable is a single character such as A, *, x, or a space character . Variable declares by single-quote.

char c = ‘A’, char c= ‘\u0101’;

8. For the type boolean, there are precisely two literals: true and false.

boolean b = false;

There is a fundamental difference between the primitive types and the String type: Values of type String are objects. While we will not study objects in detail in next chapters, it will be useful

for you to know a little about them and about a closely related topic: classes. String declares by double-quotes.

String s = ‘Hello students! I’m a String’;

The Scanner Class

The Scanner class was introduced in Java 5.0 to make it easier to read basic data types from a character input source. It does not solve the problem completely, but it is a big improvement. The Scanner class is in the package java.util.


Scanner standardInputScanner = new Scanner( System.in );

System.in – allows input from command line



Section 1.

Exercise 1:


package com;

class Interest{

public static void main(String args[]){

/* Declare the variables. */

double principal; // The value of the investment.

double rate; // The annual interest rate.

double interest; // Interest earned in one year.


/* Initialize variables. */

principal = 17000;

rate = 0.07;

interest = principal * rate; // Compute the interest.

principal = principal + interest;

// Compute value of investment after one year, with interest.

// (Note: The new value replaces the old value of principal.)

/* Output the results. */

System.out.print("The interest earned is $");


System.out.print("The value of the investment after one year is $");


} // end of main()

} // end of class Interest

Solve together:

This class implements a simple program that will compute the amount of interest that is earned on $17,000 invested at an interest rate of 0.07 for one year. The interest and the value of the investment after one year are printed to standard output.



Exercise 2:


package com;

import java.util.Scanner;

public class ScannerTest {

public static void main(String args [])


/*Declare variables*/

String name;

// create class Scanner

Scanner input = new Scanner(System.in);

System.out.println("Enter your name : ");

// wait until user enters his/her name

name = input.nextLine();

System.out.println("How are you "+name+"?");

} //end of main()

} // end of ScannerTest


Solve together:

In this program, class will implement Scanner class from library java.util as we told before. Program will ask user to input his / her name from command line (System.in). Then will wait until enter button presses. When user enter Enter button, displays output shown below.




Section 2.


1. Write a program that will print your initials to standard output in letters that are nine lines tall. Each big letter should be made up of a bunch of *’s. For example, if your initials were “DJE”, then the output would look something like:



2. Write a program that asks the user’s name, and then greets the user by name. Before outputting the user’s name, convert it to upper case letters. For example, if the user’s name is Aydin, then the program should respond “Hello, AYDIN, nice to meet you!”.

3. Write an application that asks user to enter two integers, obtains them from the user and prints their sum, product, difference and quotient (division).

4. Given two strings, a and b, print the result of putting them together in the order abba, e.g. "Hi" and "Bye" returns "HiByeByeHi".

5. Given three ints, a b c, display true if it is possible to add two of the ints to get the third.


input output
1,2,10 True
1,2,3 False
4,1,3 True

Given three ints, a b c, return true if one of b or c is "close" (differing from a by at most 1), while the other is "far", differing from both other values by 2 or more. Note: Math.abs(num) computes the absolute value of a number.



7. Implement a Java-main-method that prints out the multiplication table for all numbers from 1 to 10. Use the tabulator character '\t' to align the values. The output of your method should be as follows:

1 2 3 4 5 6 7 8 9 10

2 4 6 8 10 12 14 16 18 20

3 6 9 12 15 18 21 24 27 30

4 8 12 16 20 24 28 32 36 40

5 10 15 20 25 30 35 40 45 50

6 12 18 24 30 36 42 48 54 60

7 14 21 28 35 42 49 56 63 70

8 16 24 32 40 48 56 64 72 80

9 18 27 36 45 54 63 72 81 90

10 20 30 40 50 60 70 80 90 100


8. Implement a Java-method with three local int variables a, b, and c that sorts these three values in ascending order by comparing and exchanging their values. At the end of the program a <= b <= c must hold.

9. Implement a Java-method that prints out the day of the week for a given day (1..31), month (1..12) and year.



Algorithm, Searching Algorithms


A program is an expression of an idea. A programmer starts with a general idea of a task

for the computer to perform. Presumably, the programmer has some idea of how to perform

the task by hand, at least in general outline. The problem is to flesh out that outline into a

complete, unambiguous, step-by-step procedure for carrying out the task. Such a procedure is

called an “algorithm.” (Technically, an algorithm is an unambiguous, step-by-step procedure

that terminates after a finite number of steps; we don’t want to count procedures that go on

forever.) An algorithm is not the same as a program.

Finally, a program is written in some particular programming language. An algorithm is more like the idea behind the program, but it’s the idea of the steps the program will take to perform its task, not just the idea of the task itself. An algorithm can be expressed in any language, including English.

Pseudocode:Is an informal language that helps programmers develop algorithms without having to worry about the strict details of Java language syntax. The pseudocode we present is particularly useful for developing algorithms that will be converted to structured portions of Java programs. Pseudocode is similar to everyday English. It is convenient and user friendly, but it is not an actual computer programming language.

Pseudocode does not execute on computers. Rather, it helps the programmer "think out" a program before attempting to write it in a programming language, such as Java. This chapter provides several examples of how to use pseudocode to develop Java programs.

if Single-Selection Statement Programs use selection statements to choose among alternative courses of action. For example, suppose that the passing grade on an exam is 60. The pseudocode statement

If student's grade is greater than or equal to 60 then
Print "Passed"

In java code it looks like:

if ( studentGrade >= 60 )

System.out.println( "Passed" );

if...else Double-Selection Statement The if single-selection statement performs an indicated action only when the condition is true; otherwise, the action is skipped. The if...else double-selection statement allows the programmer to specify an action to perform when the condition is true and a different action when the condition is false. For example, the pseudocode statement

If student's grade is greater than or equal to 60
Print "Passed"
Print "Failed"

In java code it looks like

if ( grade >= 60 )

System.out.println( "Passed" );


System.out.println( "Failed" );

Increment (++) and Decrement (--) Operators Java provides two unary operators for adding 1 to or subtracting 1 from the value of a numeric variable. These are the unary increment operator, ++, and the unary decrement operator, --. A program can increment by 1 the value of a variable called v using the increment operator, ++, rather than the expression v = v + 1 or v += 1. You can see examples from table shown below:

Operator Expression Explanation
++ ++a Increment a by 1, then use the new value of a in the expression in which a resides.
-- b-- Use the current value of b in the expression in which b resides, then decrement b by 1.



Precedence rules: If you use several operators in one expression, and if you don’t use parentheses to explicitly

indicate the order of evaluation, then you have to worry about the precedence rules that determine the order of evaluation.

Precedence table

Unary operators ++, -- , ! , unary - and +
Multiplication and division *, /, %
Addition and subtraction +, -
Relational operators <, >, <=, >=
Equality and inequality ==, !=
Boolean and &&
Boolean or | |
Conditional operator ? :
Assignment operators =, +=, -=, *=, /=, %=

Searching Algorithms. Binary Search: A binary search algorithm is a technique for finding a particular value in a linear array, by ruling out half of the data at each step. A binary search finds the median, makes a comparison to determine whether the desired value comes before or after it, and then searches the remaining half in the same manner. A binary search is an example of a divide and conquer algorithm (more specifically a decrease and conquer algorithm) and a dichotomic search. There are many Searching Algorithms like Linear Search, Binary Search and etc. We will show only Binary Search with pseudocode and java code.

· Pseudocode:

Assume sorted data M(0) … M(n)

Binsearch (x)

left = 0

right = n

midpoint = (left + right) / 2

WHILE x notequal M(midpoint)

midpoint = (left + right) / 2

IF M(midpoint) < x THEN left = midpoint

ELSE right = midpoint


· Java Code:

public int binarySearch(int[] search, int find) {
int start, end, midPt;
start = 0;
end = search.length - 1;
while (start <= end) {
midPt = (start + end) / 2;
if (search[midPt] == find) {
return midPt;
} else if (search[midPt] < find) {
start = midPt + 1;
} else {
end = midPt - 1;
return -1;



Section 1.

Exercise 1:


public class Increment


public static void main( String args[] )


int c;

// demonstrate postfix increment operator

c = 5; // assign 5 to c

System.out.println( c ); // print 5

System.out.println( c++ ); // print 5 then postincrement

System.out.println( c ); // print 6


System.out.println(); // skip a line


// demonstrate prefix increment operator

c = 5; // assign 5 to c

System.out.println( c ); // print 5

System.out.println( ++c ); // preincrement then print 6

System.out.println( c ); // print 6


} // end main


Solve together: In this example, we simply want to show the mechanics of the ++ operator, so we use only one class declaration containing method main. Occasionally, when it does not make sense to try to create a reusable class to demonstrate a simple concept, we will use a mechanical example contained entirely within the main method of a single class.



Section 2


1. Write an application that uses only the output statements

System.out.print( "* " );

System.out.print( " " );


to display the checkerboard pattern that follows. Note that a System.out.println method call with no arguments causes the program to output a single newline character.


2.Write an application that reads three nonzero integers and determines and prints whether they could represent the sides of a right triangle.  


3.A large company pays its salespeople on a commission basis. The salespeople receive $200 per week plus 9% of their gross sales for that week. For example, a salesperson who sells $5,000 worth of merchandise in a week receives $200 plus 9% of $5,000, or a total of $650. You have been supplied with a list of the items sold by each salesperson. Develop a Java application that inputs one salesperson's items sold for last week and calculates and displays that salesperson's earnings. There is no limit to the number of items that can be sold by a salesperson.

Item Value

4. Write a Java application that uses looping to print the following table of values: (Hint: you can use printf).

N 10*N 100*N 1000*N


5. How many times do you have to roll a pair of dice before they come up snake eyes? You could do the experiment by rolling the dice by hand. Write a computer program that simulates the experiment. The program should report the number of rolls that it makes before the dice come up snake eyes. (Note: “Snake eyes” means that both dice show a value of 1.)



Java Loops. Logical Operator

In this chapter, we demonstrate Java's for, do...while and switch statements. Through a series of short examples using while and for, we explore the essentials of counter-controlled repetition. We introduce the break and continue program control statements. We discuss Java's logical operators, which enable programmers to use more complex conditional expressions in control statements.

Finally, we summarize Java's control statements and the proven problem-solving techniques presented in previous chapters.

while Repetition Statement A repetition statement allows the programmer to specify that a program should repeat an action while some condition remains true. The pseudocode statement: while ( < condition > ) { <statement > }

for Repetition Statement Java provides the for repetition statement, which specifies the counter-controlled-repetition details in a single line of code. The general format of the for statement is

for ( < initialization ; condition; increment >)

< statement >


initialization - loop's control variable and provides its initial value;

condition - determines whether the loop should continue executing;

increment - modifies the control variable's value (increment or decrement);

statement – any java statements, which ends with semicolon;

Be careful we have also two semicolons between them.

do . . while Repetition Statement The do...while repetition statement is similar to the while statement. The difference is, in the while, the program tests the loop-continuation condition at the beginning of the loop, before executing the loop's body. If the condition is false, the body never executes. The do...while statement tests the loop-continuation condition after executing the loop's body; therefore, the body always executes at least once. When a do...while statement terminates, execution continues with the next statement in sequence. The general format of the do..while loop is:

< statement >
} while ( < condition > );

Also we have semicolon at the end of while statement.

break and continue Statements Java provides statements break and continue to alter the flow of control. The preceding section showed how break can be used to terminate a switch statement's execution. This section discusses how to use break in a repetition statement. In addition to the break and continue statements discussed in this section, Java provides the labeled break and continue statements for use in cases in which a programmer needs to conveniently alter the flow of control in nested control statements.

The break statement, when executed in a while, for, do...while or switch, causes immediate exit from that statement. Common uses of the break statement are to escape early from a loop or to skip the remainder of a switch. The continue statement, when executed in a while, for or do...while, skips the remaining statements in the loop body and proceeds with the next iteration of the loop.

You will see examples in Examples section.


Logical Operators Java provides logical operators to enable programmers to form more complex conditions by combining simple conditions. The logical operators are && (conditional AND), || (conditional OR), & (boolean logical AND), | (boolean logical inclusive OR), ^ (boolean logical exclusive OR) and ! (logical NOT). Let’s talk about each of them one by one. Truth table may be useful for you (fig - 4.1).

Conditional AND (&&) Operator Suppose that we wish to ensure at some point in a program that two conditions are both true before we choose a certain path of execution. In this case, we can use the AND operator, as follows:

if ( gender == FEMALE && age >= 65 )

This if statement contains two simple conditions. The condition gender == FEMALE compares variable gender to the constant FEMALE. This might be evaluated, for example, to determine whether a person is female. The condition age >= 65 might be evaluated to determine whether a person is a senior citizen.

Conditional OR ( || ) Operator Now suppose that we wish to ensure that either or both of two conditions are true before we choose a certain path of execution. In this case, we use the OR operator, as in the following program segment:

if ( ( semesterAverage >= 90 ) || ( finalExam >= 90 ) )

System.out.println ( "Student grade is A" );

Boolean Logical AND (&) and Boolean Logical OR (|) Operators The boolean logical AND (&) and boolean logical inclusive OR (|) operators work identically to the && (conditional AND) and || (conditional OR) operators, with one exception: The boolean logical operators always evaluate both of their operands.

For example: Boolean Logic AND Operant: if ( gender == 1 ) & ( age >= 65 ) if ( gender == 1 ) & ( age >= 65 ) sdsdsdsdsdsdsdsd In this example, program will check both, two situations. The value of gender and age. If value of gender is not equal to 1, program will check the value of age. Conditional AND Operant: if ( gender == 1 ) & ( age >= 65 ) if ( gender == 1 ) && ( age >= 65 ) sdsdsdsdsdsdsdsd In this example, program will check both, two situations. The value of gender and age. But, if the value of gender is not equal to 1, program will not check the value of age.

Logical Negation (!) Operator The ! (logical NOT) operator enables a programmer to reverse the meaning of a condition. Unlike the logical operators &&, ||, &, | and ^, which are binary operators that combine two conditions, the logical negation operator is a unary operator that has only a single condition as an operand. boolean passed = true; if ( ! passed ) System.out.printf( "You do not passed!");

Truth table (fig – 4.1)

X Y X & Y X | Y X ^ Y !X

Factorial Factorial n (usually written n!) is the product of all integers up to and including n (1 * 2 * 3 * ... * n). This problem is often used as a programming example, especially to show how to write recursive functions.




Section 1

Exercise 1:

Java code:

public class ForTest {

public static void main(String[] args) {

for (int i = 1; i <= 10; i++)









Solve together: Our Program prints out all even numbers from 1 till 10. This class creates for statement in its main method. And initialize the value of i to 1, then increments each time by 1 (i = i+1), while the value of i less than or equal to 10. The if statement will check, Does the value of i divisible by 2 or not. If divisible, then print out this value.


Exercise 2:


import java.util.Scanner;

public class WhileTest


public static void main(String[] args)


Scanner in = new Scanner(System.in);

int count = 0; // count how many divisions we've done

int number;

System.out.println("Enter your number");

number = in.nextInt();

while (number >= 1) {

number = number / 2;



System.out.println("Answer is : "+count);



Solve together:

1. Here's a while loop example that uses a loop to see how man times you can divide a number by 2. Given a number, shows how many times can we divide it by 2 to get down to 1.



Exercise 3:

Java Code:

public class DoWhileTest {

public static void main(String[] args)


int i = 0;



if(i%2==0 && i != 0)








Solve together: This program works as same as previous example ( ForTest ), but little bit differ. As you can see we used do .. while repetition statement. Program initialize the value of i = 0. Before looking for the given condition, our program checks the if statement. And also we have logical NOT operand and Conditional AND operand. In human words, if the value of i is divisible by 2 (even) AND NOT equal to 0, then print the value of i. Because, initial value of i is equal to 0. Then increment the value of i. The output same as ForTest.



Section 2


1. Write a simple program, that user enters his or her final grade (in digits) and your program will show result in letters. For example, if user enters 90 your program will print out “A-”. Also, if user enters less than 0 and bigger than 100 print out an exception.


A [ 95-100 ]
A- [ 90-95 )
B+ [ 85-90 )
B [ 80-85)
B- [ 75-80)
C+ [ 70-75)
C [ 65-70)
C- [ 60-65)
D+ [ 55-60)
D [ 50-55)
F [0-50)

Date: 2015-12-24; view: 2664

<== previous page | next page ==>
 | Group 1: military, space, nuclear power
doclecture.net - lectures - 2014-2024 year. Copyright infringement or personal data (0.054 sec.)