Basics of Java
Basics of Java
Lecture
Performing Basic
Tasks
in Java
Naming Conventions
Things to Remember
Taking in command line arguments
Primitives vs. Objects
Understanding Basics
Naming Conventions
MyClass
myMethod()
myVariable
MY_CONSTANT
Things to remember
Name of file must match name of class
It is case sensitive
System.out.println, System.out.print
An idiom explained
You will see the following line of code often:
About main()
Why public?
Why static ?
Things to Remember
+ operator when used with Strings concatenates them
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 .out.println (Hello + i) // will print Hello 4 on screen
However
System,.out..println( i+j) ; // will print 9 on the console
String Concatenation
public class StringTest {
Taking in Command
Line Arguments
class Object , except a few primitive data types, which are there for
efficiency reasons.
Primitive data types are generally used for local variables, parameters and
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
Stack
Heap
num
5
0F59
name
st
0F59
ali
Primitives (cont)
For all built-in primitive data types java uses
Wrapper Classes
Wrapper Classes
Each primitive data type
provides additional
functionality (conversion,
size checking etc), which a
primitive data type can not
provide
Primitive
Data Type
byte
short
int
long
float
double
char
boolean
Corresponding
Object Class
Byte
Short
Integer
Long
Float
Double
Character
Boolean
Wrapper Use
You can create an object of Wrapper class using a
Heap
num
04E2
numObj
04E2
10
Wrapper Uses
Defines useful constants for each data type
For example,
Integer.MAX_VALUE
Input / Output
System.out.print()
Does not print the end of line
Does not force a flush
Selection Structures
if-else and switch
Boolean Operators
==, !=
&&, ||
Logical negation.
Control Structures
for, while & do-while
Looping Constructs
while
while (continueTest) {
body;
}
do
do {
body;
} while (continueTest);
// ^ dont 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++) {
System.out.println("hello from for");
}
// while loop
int j = 1;
while (j <= 5) {
System.out.println("Hello from while");
j++;
}
//do while loop
int k =1;
do{
System.out.println("Hello from do-while");
k++;
}while(k <= 5);
}
}