Java - 2-v2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

A First Simple Program Programming

This is a simple Java program.


Call this file Example.java.
Multiple line comments (comment are ignored by the compiler).
class Example {
Writing Simple Program A Java program begins with
Prepared By Dr. Muhammad Mazin a call to main().
Single line comments
public static void
--------------------------------------------------------------------------------------- main(String[] args) {
System.out.println("Java
References:
drives the Web.");
1. Java an Introduction to Problem Solving and Programming, Walter Savitch, 7 th ed. }
2. Java - A Beginner's Guide, Herbert Schildt, 9th ed. ◼ } Java is case sensitive.
◼ The Java compiler requires that a source file use the .java filename extension.
◼ In Java, all code must reside inside a class.
◼ By convention, the name of the main class should match the file name that holds the program (case sensitive).

A First Simple Program Programming A First Simple Program Programming


This is a simple Java program.
class Example { Call this file Example.java. public static void main(String[] args) {
◼ This line uses the keyword class to declare that a ◼ In this case, main( ) must be declared as public, since it must be called by code outside of its class when the
class Example { program is started.
new class is being defined. A Java program begins with
◼ Example is the name of the class. a call to main(). ◼ The keyword static allows main( ) to be called before an object of the class has been created. This is necessary
public static void because main( ) is called by the JVM before any objects are made.
◼ The class definition begins with the opening curly main(String[] args) {
◼ The keyword void simply tells the compiler that main( ) does not return a value. As you will see, methods may
brace “{“ and ends with the closing curly brace “}”. System.out.println("Java
drives the Web."); also return values.
public static void main(String[] } ◼ Any information that you need to pass to a method should be passed as a parameter. If there is no parameters you
}
◼args) { first line of main( ) method.
This is the still need to include the empty parentheses.
◼ In main( ) there is only one parameter, String[ ] args, which declares a parameter named args of type string array.
◼ Java applications begin execution by calling main( ) method.
◼ The last character on the line is the “{“ this means that the main method body start.
◼ The public keyword is an access modifier it is used to determines how other parts of the program
can access the members of the class. When a class member is preceded by public, then that member
can be accessed by code outside the class in which it is declared. (The opposite of public is private,
which prevents a member from being used by code defined outside of its class.)
A First Simple Program Programming Java Identifiers
This is a simple Java program.
System.out.println("Java drives Call this file Example.java.
◼ The technical term for a name in a programming language, such as the name of a variable, is
the Web."); called an identifier.
class Example { ◼ Identifier (a name) can contain only letters, digits 0 through 9, and the underscore character (_).
◼ This line outputs the string “Java drives the A Java program begins with
a call to main(). ◼ Avoid the use of reserved keywords (int, if, class, …)
Web.” followed by a new line. public static void
main(String[] args) { ◼ The first character in an identifier must be letter
◼ Output is accomplished by the built-in println(
System.out.println("Java ◼ Java is case sensitive. Java considers mystuff, myStuff, and MyStuff to be three different
) method. drives the Web.");
} identifiers, and you could have three different variables with these three names.
◼ System is a predefined class that provides } ◼ There is a convention that is usually followed in javain which the names of classes start with an
access to the system, and out is the output uppercase letter, and the names of variables and methods start with a lowercase letter.
stream that is connected to the console. ◼ Example of a legal identifies (inputStream YourClass CarWash hotCar theTimeOfDay)
◼ The statement ends with a semicolon, it is an ◼ Example of a illegal identifies (prenhall.com go-team Five* 7eleven)
important part of the Java syntax.
◼ Java is case sensitive language.

Handling Syntax Errors Simple Programs class Example2 {


public static void main(String[]
◼ If you enter the program incorrectly, the compiler will report a syntax error message. ◼ A variable is a named memory location that can be Code
args) {
assigned a value. int myVar1; this declares
◼ The reported error may not always reflect the actual cause of the problem. a variable
◼ The value of a variable can be changed during the int myVar2; this declares
◼ In the previous program, an accidental omission of the opening curly brace after the main( ) execution of a program. another variable
method causes the compiler to report the following two errors: myVar1 = 1024; this
◼ All variables must be declared before they are used. assigns 1024 to myVar1
System.out.println("myVar1
◼ It is a good programming behavior to chose a
contains " + myVar1);
meaningful variable names. myVar2 = myVar1 / 2;
◼ The type of values that the variable can hold must be System.out.print("myVar2
contains myVar1 / 2: ");
specified. (this is called the type of the variable)
◼ The first error message is wrong because what is missing is not a semicolon, but a curly brace. System.out.println(myVar2);
◼ Precede the variable name with int keyword means the Output
}
◼ When your program contains a syntax error, you shouldn’t necessarily take the compiler’s }
variable can hold integer values (whole number values,
messages at face value. The messages may be misleading. with no fractions).
◼ Sometimes the error will be reported several lines after the location of the error. ◼ The line of code “myVar1 = 1024;” assign
myVar1 the value 1024.
Simple Programs class Example2 { Simple Programs class Example2 {
public static void main(String[] public static void main(String[]
◼ The assignment operator is the single equal sign, It Code
args) { ◼ It is possible to declare two or more variables using Code
args) {
copies the value on its right side into the variable on int myVar1; this declares the same declaration statement. Just separate their int myVar1; this declares
a variable a variable
its left. names by commas. For example, myVar1 and
int myVar2; this declares int myVar2; this declares
System.out.println("myVar1 contains " another variable myVar2 could have been declared like this: another variable
+ myVar1); myVar1 = 1024; this int myVar1, myVar2; myVar1 = 1024; this
assigns 1024 to myVar1 assigns 1024 to myVar1
◼ This line of code outputs the string "myVar1 contains " System.out.println("myVar1 System.out.print("myVar2 contains System.out.println("myVar1
followed by the value of myVar1. contains " + myVar1); myVar1 / 2: "); contains " + myVar1);
myVar2 = myVar1 / 2; myVar2 = myVar1 / 2;
◼ Using the + operator, you can chain together as many items
System.out.print("myVar2
System.out.println(myVar2); System.out.print("myVar2
as you want within a single println( ) statement.
contains myVar1 / 2: "); ◼ The print( ) method is just like println( ), except that contains myVar1 / 2: ");
myVar2 = myVar1 / 2; System.out.println(myVar2); print() does not output a new line after each call. System.out.println(myVar2);
Output
} Output
}
◼ This line divides the value in myVar1 by 2 and then stores } ◼ Both print( ) and println( ) can be used to output values of }
that result in myVar2. any of Java’s built-in types.
◼ After the line executes, myVar2 will contain the value 512.
◼ The value of myVar1 will not change.

Simple Programs
public class EggBasket Simple Programs class Example2 {
{ public static void main(String[]
public static void main(String[] args) ◼ It is possible to declare two or more variables using Code
args) {
{ int myVar1; this declares
int numberOfBaskets, eggsPerBasket, the same declaration statement. Just separate their
a variable
totalEggs; names by commas. For example, myVar1 and
numberOfBaskets = 10; int myVar2; this declares
myVar2 could have been declared like this: another variable
eggsPerBasket = 6;
totalEggs = numberOfBaskets *
int myVar1, myVar2; myVar1 = 1024; this
eggsPerBasket; assigns 1024 to myVar1
System.out.println("If you have"); System.out.print("myVar2 contains System.out.println("myVar1
System.out.println(eggsPerBasket + " contains " + myVar1);
eggs per basket and");
myVar1 / 2: ");
myVar2 = myVar1 / 2;
System.out.println(numberOfBaskets + System.out.println(myVar2); System.out.print("myVar2
" baskets, then");
◼ The print( ) method is just like println( ), except that contains myVar1 / 2: ");
System.out.println("the total number
of eggs is " + totalEggs); print() does not output a new line after each call. System.out.println(myVar2);
} Output
}
}
◼ Both print( ) and println( ) can be used to output values of }
any of Java’s built-in types.
Keyboard Input Keyboard Input
import java.util.Scanner;
public class RectangleArea Enter the width of a rectangle in cm:
public class EggBasket
{ 10 {
public static void main(String[]
Enter the height of a rectangle in cm: public static void main(String[] args)
5
args) the area of the rectangle is:50
{
{ Process finished with exit code 0 int numberOfBaskets, eggsPerBasket,
totalEggs;
int width, height, area;
◼ We use the class Scanner to accept keyboard input. numberOfBaskets = 10;
Scanner keyboard = new
eggsPerBasket = 6;
Scanner(System.in); ◼ This line “ import java.util.Scanner;” import the totalEggs = numberOfBaskets *
System.out.println("Enter the definition of the scanner class from the package java. eggsPerBasket;
width of a rectangle: "); util. System.out.println("If you have");
width = keyboard.nextInt(); System.out.println(eggsPerBasket + "
System.out.println("Enter the ◼ The line “ Scanner keyboard = new eggs per basket and");
height of a rectangle: "); Scanner(System.in);” sets things up so that data System.out.println(numberOfBaskets +
height = keyboard.nextInt(); can be entered from the keyboard, this line must " baskets, then");
area = width * height; appear before getting any input from the keyboard. System.out.println("the total number
System.out.print("the area of of eggs is " + totalEggs);
the rectangle is: " + area ); ◼ This line “Scanner keyboard = new }
} Scanner(System.in);” the value of the expression }
} to the right (Keyboard input) and gives it to the

Data Types Data Types


▪ To assign a character to variable use single quotation for example varName = 'B’;
▪ To assign integer types, such as 2, 3, 0, 23, or 752 . An integer vale can be prefaced with a
plus sign or a minus sign, as in +12 and -72.
▪ Numeric values cannot contain commas, “1,000” is not correct in Java.
▪ Floatingpoint number may be written in either of two forms:
▪ The simple form, like 2.54568
▪ The scientific notation:
• usually called e notation or floatingpoint notation
• The number 8.65 × 10 8 (equal to 865000000.0) can be written in java like this
8.65e8
• The number 4.83 3 1024, which is equal to 0.000483, could be written in Java as
either 0.000483 or 4.83e-4 or 0.483e-3 or 48.3e-5 .
• The number after the e cannot contain a decimal point.
Data Types Data Types
◼ The numbers 5 and 5.0 are conceptually the same number. But Java considers them to be ◼ You cannot even put the double of value 3.5 “or even 3.0” in a variable of type int.
different. Thus, 5 is an integer constant of type int, but 5.0 is a floating-point constant of type ◼ you can assign a value of any type in the following list to a variable of any type that
double.
appears further down in the list:
◼ Floating point numbers are stored with a limited amount of precision.
For example, you can assign a value of type long to a variable of type float or to a
◼ If it can store only ten digits after the decimal, then one third is stored as 0.3333333333 (and no
variable of type double.
more 3s)
but you cannot assign a value of type long to a variable of type byte, short, or int.
◼ The type char is used for single characters, such as letters, digits, or punctuation.
◼ You can assign a value of type char to a variable of type int or to any of the numeric types
that follow int in our list of types (note that cannot assign a value of type char to a
variable of type byte).

◼ A single character is enclosed with single quotes 'A'.


◼ Remember that uppercase letters and lowercase letters are different characters.
◼ The convention for naming the primitive types in Java is to begin them with a lowercase letter.

Type Casting ASCII numbering system


◼ Type cast changes the data type of a value from its normal type to some other type. For ◼ ASCII is a standard data-transmission code that is used by the
example, changing the type of the value 2.0 from double to int involves a type cast.
computer for representing both the textual data and control characters.
◼ In Java, an ASCII table is a table that defines ASCII values for each
character.
◼ You cannot assign a value of type double to a variable of type int, even if the value of type
double happens to have all zeros after the decimal point ◼ Basically, they just wrote down all the characters and then numbered
them in the order they were written down.
◼ The following type cast will produce the int value corresponding to the
◼ In order to assign a value of type double to a value of type int, you must place (int) in front
character '7’
of the value or the variable holding the value.

◼ If the value of distance is 25.99, the value of (int)distance is 25 not 26. It displays the number 55 because character '7' just happened to get
the number 55.
◼ The following command will display the character ‘A’
ASCII Table Named Constants
◼ A constants value cannot be changed, it need to have a fixed value (For example, 'A', 'B’, 5, 2.7)
◼ Constant can be initialize only one time using this syntax:
finalType Variable = Constant ;

▪ For example, we can give the name PI to the constant 3.14159 as follows:
public static final double PI = 3.14159;

▪ The convention for naming constants is to use all uppercase letters, with an underscore symbol (_)
between words. For example:
final int DAYS_PER_WEEK = 7;
final int MAX_STRIKES = 3;
final double INTEREST_RATE = 6.99;
final String MOTTO = "The customer is right!";
final char SCALE = 'K';

Named Constants
import java.util.Scanner;
public class CircleArea
{
public static void main(String[] args)
{
double r, area;
final double PI=3.14159; Thank You
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the radius if the
circle in cm.: ");
r = keyboard.nextInt();
Question are Welcome
area = r * PI;
System.out.print(“The area of the rectangle
is: " + area + "square cm.");
}
}
Enter the radius if the circle in cm.:
5
The area of the rectangle is: 15.70795 square cm.

You might also like