JAVA SYNTAX
BY MUHAMMAD ABU BAKAR
WRITING BASIC JAVA PROGRAM
SYNTAX FOR C++ PROGRAMMERS
SOFTWARE REQUIREMENTS
• For the start following software will do the job
• You need to have the latest version of JDK. (J2SE 5.0) You can
download it for free from
[Link]
A little older versions such JDK 1.4 or 1.3 will also work
• Notepad
• And you should set your path variable.
CANONICAL EXAMPLE
HELLOWORLD APPLICATION IN JAVA
/* The HelloWorldApp class implements an application that simply displays
"Hello World!" to the standard output. */
public class HelloWorldApp {
public static void main(String[] args) {
//Display the string. No global main
[Link]("Hello World!"); }
}
COMPILING AND RUNNING
THE PROGRAM
• Save this file in some directory and compile it using
• javac [Link]
• Run the compiled file by using the command
• java HelloWorldApp
JAVA PROGRAM DEVELOPMENT AND EXECUTION
STEPS
• Java Systems
• Consist of environment, language, Java Applications
Programming Interface (API)
• Java programs have five phases
1. Edit
• .java extension
2. Compile
• javac command: javac [Link]
• Creates .class file containing bytecodes with similar name
JAVA PROGRAM DEVELOPMENT AND EXECUTION
STEPS…
3. Loading
• Class loader transfers .class file into memory
• Classes loaded and executed by interpreter with java
command
• To load,
appletviewer [Link]
OR
java MyProgram
JAVA PROGRAM DEVELOPMENT AND EXECUTION
STEPS…
4. Verify
• Bytecode verifier makes sure bytecodes are valid and do
not violate security
5. Execute
• Computer interprets program one bytecode at a time
• Performs actions specified in program
Program is created in
Phase 1 Editor Disk the editor and stored
on disk.
Compiler creates
Phase 2 Compiler Disk bytecodes and stores
them on disk.
Primary
Memory
Class Loader
Phase 3
Class loader puts
bytecodes in memory.
Disk
..
..
..
Primary
Memory
Bytecode Verifier
Phase 4 Bytecode verifier
confirms that all
bytecodes are valid
and do not violate
Java’s security
.. restrictions.
..
..
Primary
Interpreter Memory Interpreter reads
Phase 5 bytecodes and
translates them into a
language that the
computer can
understand, possibly
.. storing data values as
.. the program executes.
..
UNDERSTANDING BASICS
• Naming Conventions
• MyClass
• myMethod()
• myVariable
• MY_CONSTANT
PERFORMING BASIC
TASKS
IN JAVA
TOPICS
• Things to Remember
• Taking in command line arguments
• Primitives vs. Objects
• Wrapper classes and Conversions
• Taking Input and Output using Swing
• Selection and Control Structures
• OOP in java (Defining and using class)
THINGS TO REMEMBER
• Name of file must match name of class
• It is case sensitive
• Processing starts in main
• public static void main(String[] args)
• Printing is done with [Link]
• [Link], [Link]
• Compile with “javac”
• Open DOS/command prompt window; work from
there
• Supply full case-sensitive file name (with file
extension)
• Execute with “java”
AN IDIOM EXPLAINED
• You will see the following line of code often:
• public static void main(String args[]) { …}
• About main()
• “main” is the function from which your program
starts
• Why public?
• So that run time can call it from outside
• Why static ?
• it is made static so that we can call it without creating an
object
• What is String args[] ?
• Way of specifying input at startup of application
THINGS TO REMEMBER
• “+” operator when used with Strings concatenates them
• [Link](“Hello” + “World”) will produce Hello World
on console
• String concatenated with any other data type such as int will
also convert that datatype to String and the result will be a
concatenated String displayed on console
• For Example
• int i = 4
• int j = 5 ;
• System .[Link] (“Hello” + i) // will print Hello 4 on screen
• However
• System,.out..println( i+j) ; // will print 9 on the console
• For comparing Strings never use == operator, use
equals methos.
• == compares addresses (shallow comparison) while equals
compares values (deep comparison)
• E.g [Link](string2)
STRING CONCATENATION
public class StringTest {
public static void main(String[] args) {
int i = 4;
int j = 5;
[Link]("Hello" + i);
[Link](i + j);
String s1 = new String (“pakistan”);
String s2 = “pakistan”;
if (s1 == s2) {
[Link](“comparing string using == operator”);
}
if ([Link]( s2) ) {
[Link](“comparing string using equal method”);
}
}
COMPILE AND EXECUTE
TAKING IN COMMAND
LINE ARGUMENTS
TAKING IN COMMAND LINE
ARGUMENTS
/* This program will take two arguments Hello World from the
command prompt and prints them to standard console. If you
specify less than two arguments an exception will be thrown */
public class TwoArgsApp {
public static void main(String[] args) {
//Displays the first argument on console
[Link](“First argument “ +
args[0]);
//Displays the second argument on console
[Link](“Second argument “ + args[1]);
}
PASSING ANY NUMBER OF
ARGUMENTS
/* This program is able to receive any number of arguments and prints them to
console using for loop. In java, arrays knows about their size by using length
property
*/
public class AnyArgsApp {
public static void main(String[] args) {
for (int i=0; i<[Link]; i++)
{
// The “+” operator here works similar to “<<“ operator in C++. This line
is // equivalent to
cout<<“Arguments:”<<i<<“value”<<args[i];
// where cout is replaced by [Link], and “<<“ is
replaced by + for // concatenation
[Link](“Argument:” + i + “value: ” + args[i] );
}
COMPILE AND EXECUTE
PRIMITIVES VS. OBJECTS
PRIMITIVES VS. OBJECTS
• Everything in Java is an “Object”, as every class by default inherits from
class “Object” , except a few primitive data types, which are there for
efficiency reasons.
• Primitive Data Types
• 8 Primitive Data types of java
• boolean, byte 1 byte
• char, short 2 bytes
• int, float 4 bytes
• long, double 8 bytes
• Primitive data types are generally used for local variables, parameters and
instance variables (properties of an object)
• Primitive datatypes are located on the stack and we can only access their
value, while objects are located on heap and we have a reference to these
objects
• Also primitive data types are always passed by value while objects are
always passed by reference in java. There is no C++ like methods
STACK VS. HEAP
Stack Heap
public static void main(String args[])
{
int num= 5; num
5
Student st = new Student();
} 0F59
name
ali
st
0F59
PRIMITIVES (CONT)
• For all built-in primitive data types java uses lowercase. E.g int , float
etc
• Primitives can be stored in arrays
• You cannot get a reference to a primitive
• To do that you need an Object or a Wrapper class
WRAPPER CLASSES
WRAPPER CLASSES
• Each primitive data type
has a corresponding Primitive Corresponding
object (wrapper class) Data Type Object Class
byte Byte
short Short
• These Wrapper classes int
long
Integer
Long
provides additional float Float
functionality double Double
(conversion, size char Character
checking etc), which a boolean Boolean
primitive data type can
not provide
WRAPPER USE
• You can create an object of Wrapper class using a String or a
primitive data type
• Integer num = new Integer(4); or
• Integer num = new Integer(“4”);
• Num is an object over here not a primitive data type
• You can get a primitive data type from a Wrapper using the
corresponding value function
• int primNum = [Link]();
STACK VS. HEAP
Stack Heap
public static void main(String args[])
{
int num= 5; num
5
Integer numObj = new Integer (10);
}
04E2
10
numObj
04E2
WRAPPER USES
• Defines useful constants for each data type
• For example,
Integer.MAX_VALUE
• Convert between data types
• Use parseXxx method to convert a String to the
corresponding primitive data type
• String value = “532";
int d = [Link](value);
• String value = "3.14e6";
double d = [Link](value);
WRAPPERS: CONVERTING
STRINGS
Data Type Convert String using either …
byte [Link]( string )
new Byte(string ).byteValue()
short [Link]( string )
new Short(string ).shortValue()
int (stringstring
[Link]( ) )
new Integer( string ).intValue()
long [Link]( string )
new Long(string ).longValue()
float [Link]( string )
new Float(string ).floatValue()
double [Link]( string )
new Double( string ).doubleValue()
WRAPPER USES
• When a method does not except an int primitive but still you need to pass an int value, you can
use the corresponding Wrapper.
• [Link](new Integer(4) ); // this was required prior to jdk5.0 the l
• Boxing/Unboxing Conversions
• New feature added in j2se 5.0
• Boxing
• Integer iWrapper = 10;
• Prior to J2SE 5.0, we use
• Integer a = new Integer(10);
• Unboxing
• int iPrimitive = iWrapper;
• Prior to J2SE 5.0, we use
• int b = [Link]();
INPUT / OUTPUT
CONSOLE BASED OUTPUT
[Link]
• System class
• Out represents the screen
• [Link]()
• Prints the string followed by an end of line
• Forces a flush
• [Link]()
• Does not print the end of line
• Does not force a flush
• [Link]()
• Force a flush
INPUT / OUTPUT
/* This program will takes the input (number) through GUI and prints its square on the console as
well as on the GUI. */
import [Link].*;
public class InputOutputTest {
public static void main(String[] args) {
//takes input through GUI
String input = [Link]("Enter the number");
int number = [Link](input);
int square = number * number;
//Display square on console
[Link]("square:" + square);
//Display square on GUI
[Link](null, "square:"+ square);
[Link](0); //Don’t forget to write when using JOptionPane. Don’t need it in
//J2SE 5.0
}
COMPILE AND EXECUTE
SELECTION STRUCTURES
IF-ELSE AND SWITCH
IF–ELSE SELECTION STRUCTURE
/* This program will demonstrates the use of if-else selection structure.
Note that its syntax is very similar to C++
*/
public class IfElseTest {
public static void main(String[] args) {
int firstNumber = 10;
int secondNumber = 20;
//comparing first number with second number
if (firstNumber > secondNumber) {
[Link](“first number is greater than second”);
}
else if (firstNumber == secondNumber) {
[Link](“first number is equals to second number”);
}
else {
[Link](“first number is smaller than second number”);
}
COMPILE AND EXECUTE
BOOLEAN OPERATORS
• ==, !=
• Equality, inequality. In addition to comparing primitive
types, == tests if two objects are identical (the same
object), not just if they appear equal (have the same
fields). More details when we introduce objects.
• <, <=, >, >=
• Numeric less than, less than or equal to, greater than,
greater than or equal to.
• &&, ||
• Logical AND, OR. Both use short-circuit evaluation to
more efficiently compute the results of complicated
expressions.
•!
• Logical negation.
SWITCH SELECTION
STRUCTURE
import [Link].*;
public class SwitchTest {
public static void main(String[] args) {
int operand1 = 10;
int operand2 = 20;
String choice = [Link](“Enter
1 for sum, 2 for product”);
int ch = [Link](choice);
// continue….
SWITCH SELECTION
STRUCTURE…
switch(ch)
{
case 1:
int sum = operand1 + operand2;
[Link](“sum: ” + sum );
break;
case 2:
int product = operand1 * operand2;
[Link](“product: ” + product );
break;
default:
[Link](“wrong choice!”);
[Link](0);
}
}
COMPILE AND EXECUTE
CONTROL STRUCTURES
FOR, WHILE & DO-WHILE
LOOPING CONSTRUCTS
• while
while (continueTest) {
body;
}
• do
do {
body;
} while (continueTest);
// ^ don’t forget semicolon
• for
for(init; continueTest; updateOp) {
body;
}
CONTROL STRUCTURES
public class ControlStructTest {
public static void main(String[] args) {
// for loop
for (int i=1; i<= 5; i++) {
[Link]("hello from for");
}
// while loop
int j = 1;
while (j <= 5) {
[Link]("Hello from while");
j++;
}
//do while loop
int k =1;
do{
[Link]("Hello from do-while");
k++;
}while(k <= 5);
}
}
COMPILE AND EXECUTE