2. 1.10 Java Basic Syntax
• When we consider a Java program it can be defined as a collection of objects that
communicate via invoking each other's methods.
• Let us now briefly look into what do class, object, methods and instance variables mean.
❖ Object - Objects have states and behaviors.
❖ Example: A dog has states - color, name, breed as well as behaviors -wagging, barking, eating.
❖ An object is an instance of a class.
❖ Class - A class can be defined as a template/ blue print that describes
the behaviors/states that object of its type support.
❖ Methods - A method is basically a behavior.
❖ A class can contain many methods.
❖ It is in methods where the logics are written, data is manipulated and all the actions are executed.
❖ Instance Variables - Each object has its unique set of instance
variables.
❖ An object's state is created by the values assigned to these instance variable
2
3. 1.11 First Java Program:
• Let us look at a simple code that would print the words Hello
World(MyFirstJavaProgram.java).
3
public class MyFirstJavaProgram
{
/* This is my first java program.
* This will print 'Hello World' as the output
*/
public static void main(String []args)
{
System.out.println("Hello World"); // prints Hello World
}
}
4. 1.11.1 First Java Program …
• Let's look at how to save the file, compile and run the program.
• Please follow the steps given below:
1) Open notepad and add the code as above.
2) Save the file as: MyFirstJavaProgram.java.
3) Open a command prompt window and go o the directory where you
saved the class.
▪ Assume it's C:.
4) Type ' javac MyFirstJavaProgram.java ' and press enter to compile your
code.
▪ If there are no errors in your code, the command prompt will take you to the next
line (Assumption : The path variable is set).
5) Now, type ' java MyFirstJavaProgram ' to run your program.
6) You will be able to see ' Hello World ' printed on the window.
4
C : > javac MyFirstJavaProgram.java
C : > java MyFirstJavaProgram
Hello World
5. 1.11.1 Basic Syntax:
• About Java programs, it is very important to keep in mind the following points.
• Case Sensitivity - Java is case sensitive, which means identifier Hello and hello would have
different meaning in Java.
• Class Names - For all class names the first letter should be in Upper Case.
• If several words are used to form a name of the class, each inner word's first letter should be in Upper Case.
• Example class MyFirstJavaClass
• Method Names - All method names should start with a Lower Case letter.
• If several words are used to form the name of the method, then each inner word's first letter should be in Upper Case.
• Example public void myMethodName()
• Program File Name - Name of the program file should exactly match the class name.
• When saving the file, you should save it using the class name (Remember Java is case sensitive) and append '.java' to the
end of the name (if the file name and the class name do not match your program will not compile).
• Example : Assume 'MyFirstJavaProgram' is the class name.
• Then the file should be saved as 'MyFirstJavaProgram.java'
• public static void main(String args[]) - Java program processing starts from the main()
method which is a mandatory part of every Java program. 5
6. 1.11.2 Understanding first Java program
➢ class keyword is used to declare a class in java.
➢ public keyword is an access modifier which represents visibility, it means it is
visible to all.
➢ static is a keyword, if we declare any method as static, it is known as static method.
➢ The core advantage of static method is that there is no need to create object to invoke the
static method.
➢ The main method is executed by the JVM, so it doesn't require to create object to invoke
the main method.
➢ So it saves memory.
➢ void is the return type of the method, it means it doesn't return any value.
➢ main represents startup of the program.
➢ String[] args is used for command line argument.
➢ System.out.println() is used print statement.
6
7. 1.11.3 How many ways can we write a Java program
• There are many ways to write a java program.
• The modifications that can be done in a java program are given below:
1) By changing sequence of the modifiers, method prototype is not changed.
• Let's see the simple code of main method.
2) subscript notation in java array can be used after type, before variable or after
variable.
• Let's see the different codes to write the main method.
7
static public void main(String args[])
public static void main(String[] args)
public static void main(String []args)
public static void main(String args[])
8. 1.11.3 How many ways can we write a Java program
3) You can provide var-args support to main method by passing 3 ellipses (dots)
• Let's see the simple code of using var-args in main method
4) Having semicolon at the end of class in java is optional.
• Let's see the simple code.
8
public static void main(String... args)
class A
{
static public void main(String... args)
{
System.out.println("hello java4");
}
};
9. 1.11.4 Java main method signature
9
Valid Invalid
public static void main(String[] args)
public static void main(String []args)
public static void main(String args[])
public static void main(String... args)
static public void main(String[] args)
public static final void main(String[] args)
final public static void main(String[] args)
final strictfp public static void
main(String[] args)
public void main(String[] args)
static void main(String[] args)
public void static main(String[] args)
abstract public static void
main(String[] args)
10. 1.11.5 Internal Details of Hello Java Program
• Here, we are going to learn, what happens while compiling and running the
java program.
What happens at compile time?
• At compile time, java file is compiled by Java Compiler (It does not interact
with OS) and converts the java code into bytecode.
10
11. 1.11.5 Internal Details of Hello Java Program …
What happens at runtime?
• At runtime, following
steps are performed:
• Classloader: is the
subsystem of JVM that is
used to load class files.
• Bytecode Verifier: checks
the code fragments for
illegal code that can
violate access right to
objects.
• Interpreter: read
bytecode stream then
execute the instructions. 11
12. 1.11.6 Difference between JVM, JRE and JDK
JVM:
• JVM (Java Virtual Machine) is an abstract machine.
– It is a specification that provides runtime environment in which java
bytecode can be executed.
• JVMs are available for many hardware and software platforms.
• JVM, JRE and JDK are platform dependent because
configuration of each OS differs.
– But, Java is platform independent.
• The JVM performs following main tasks:
– Loads code
– Verifies code
– Executes code
– Provides runtime environment
12
13. 1.11.6 Difference between JVM, JRE and JDK
JRE:
• JRE is an acronym for Java Runtime
Environment.
– It is used to provide runtime
environment.
– It is the implementation of JVM.
– It physically exists.
– It contains set of libraries + other files
that JVM uses at runtime.
• Implementation of JVMs are also
actively released by other
companies besides Sun Micro
Systems.
13
14. 1.11.6 Difference between JVM, JRE and JDK
JDK:
• JDK is an acronym for Java
Development Kit.
• It physically exists.
• It contains JRE +
development tools.
14
15. 1.11.7 Reading data from keyboard:
1) InputStreamReader class:
• There are many ways to read data from the keyboard. For example:
1) InputStreamReader
2) Console
3) Scanner
4) DataInputStream etc.
1) InputStreamReader class:
• InputStreamReader class can be used to read data from keyboard.
• It performs two tasks:
– connects to input stream of keyboard
– converts the byte-oriented stream into character-oriented stream
❖ BufferedReader class:
• BufferedReader class can be used to read data line by line by readLine() method.
15
16. 1.11.7 Reading data from keyboard …
1) InputStreamReader class:
16
//Example of reading data from keyboard
//by InputStreamReader
//and BufferdReader class
import java.io.*;
class ReadDataISR
{
public static void main(String args[]) throws
Exception
{
String name;
int reg;
System.out.println("Enter your NAME : ");
name=readStr();
System.out.println("Enter your AGE : ");
reg=readInt();
System.out.println("Welcome
"+name+" ,your Age is "+reg);
}
static String readStr()throws Exception
{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
String str=br.readLine();
return str;
}
static int readInt()throws Exception
{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
String str=br.readLine();
int num=Integer.parseInt(str);
return num;
}
}
17. 1.11.7 Reading data from keyboard …
2) Java Console class :
• The Java Console class is be used to get input from console.
➢ It provides methods to read text and password.
• If you read password using Console class, it will not be displayed to the user.
• The java.io.Console class is attached with system console internally.
• The Console class is introduced since 1.5.
Example :Let's see a simple example to read text from console.
17
String text=System.console().readLine();
System.out.println("Text is: "+text);
18. 1.11.7 Reading data from keyboard …
2) Java Console class : Methods
How to get the object of Console:
• System class provides a static method console() that returns the unique instance of
Console class.
• Let's see the code to get the instance of Console class.
18
public static Console console(){ }
Method Description
public String readLine() Is used to read a single line of text from the console.
public String readLine(String fmt,Object... args) It provides a formatted prompt then reads the single line of
text from the console.
public char[] readPassword() Is used to read password that is not being displayed on the
console.
public char[] readPassword(String fmt,Object... args) It provides a formatted prompt then reads the password that is
not being displayed on the console.
Console c=System.console();
19. 1.11.7 Reading data from keyboard …
2) Java Console class :
19
//Example of Java Console class
//Console class provides methods to read text and password
import java.io.*;
class ReadDataConsole
{
public static void main(String args[]) throws Exception
{
Console c=System.console();
System.out.println("Enter your NAME : ");
String name=c.readLine();
System.out.println("Enter the PASSWORD : ");
char[] ch=c.readPassword();
String pass=String.valueOf(ch);//converting char array into string
System.out.println("Welcome "+name);
System.out.println("Password is: "+pass);
}
}
20. 1.11.7 Reading data from keyboard …
3) Java Scanner class :
• There are various ways to read input from the keyboard, the
java.util.Scanner class is one of them.
• The Java Scanner class breaks the input into tokens using a delimiter that is
whitespace by default.
– It provides many methods to read and parse various primitive values.
• Java Scanner class is widely used to parse text for string and primitive types
using regular expression.
• Java Scanner class extends Object class and implements Iterator and
Closeable interfaces.
20
21. 1.11.7 Reading data from keyboard …
3) Java Scanner class : Methods
21
Method Description
public String next() It returns the next token from the scanner.
public String nextLine() It moves the scanner position to the next line and
returns the value as a string.
public byte nextByte() It scans the next token as a byte.
public short nextShort() It scans the next token as a short value.
public int nextInt() It scans the next token as an int value.
public long nextLong() It scans the next token as a long value.
public float nextFloat() It scans the next token as a float value.
public double nextDouble() It scans the next token as a double value.
22. 1.11.7 Reading data from keyboard …
3) Java Scanner class : Methods
22
//Java Scanner Example to get input from console
import java.io.*;
import java.util.Scanner;
class ReadDataScanner
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter your ROLLNO: ");
int rollno=sc.nextInt();
System.out.println("Enter your NAME : ");
String name=sc.next();
System.out.println("Enter your FEE : ");
double fee=sc.nextDouble();
System.out.println("Rollno : "+rollno+"n Name:"+name+"n Fee : "+fee);
sc.close();
}
}
23. 1.11.7 Reading data from keyboard …
4) Read int from file using DataInputStream
• java.io : Class DataInputStream
• java.lang.Object
• extended by java.io.InputStream
• extended by java.io.FilterInputStream
• extended by java.io.DataInputStream
• public class DataInputStream
• extends FilterInputStream
• implements DataInput
• A data input stream lets an application read primitive Java data types from an underlying
input stream in a machine-independent way.
• An application uses a data output stream to write data that can later be read by a data input
stream.
23
24. 1.11.7 Reading data from keyboard …
4) Read int from file using DataInputStream
24
/*
Read int from file using DataInputStream
This Java example shows how to read a Java integer primitive value from file using
readInt method of Java DataInputStream class.
*/
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class ReadIntFromFile {
public static void main(String[] args) {
String strFilePath = "C://FileIO//readInt.txt";
try
{
//create FileInputStream object
FileInputStream fin = new FileInputStream(strFilePath);
25. 1.11.7 Reading data from keyboard …
4) Read int from file using DataInputStream
25
/*
* To create DataInputStream object, use
* DataInputStream(InputStream in) constructor.
*/
DataInputStream din = new DataInputStream(fin);
/*
* To read a Java integer primitive from file, use
* byte readInt() method of Java DataInputStream class.
*
* This method reads 4 bytes and returns it as a int value.
*/
int i = din.readInt();
System.out.println("int : " + i);
/*
* To close DataInputStream, use
* void close() method.
*/
din.close();
}
catch(FileNotFoundException fe)
{
System.out.println("FileNotFoundException : " + fe);
}
catch(IOException ioe)
{
System.out.println("IOException : " + ioe);
} } }
26. 1.11.7 Read character from console using InputStream
26
/*
Read character from console using InputStream
This example shows how to read a character from console window.
This example also shows how to read user entered data from console window
using System.in
*/
import java.io.IOException;
public class ReadCharFromConsoleExample {
public static void main(String[] args) {
/*
* To read a character from console use,
* read method of InputStream class variable System.in
* which defined as static variable.
*/
int iChar = 0;
System.out.println("Read user input character example");
try
{
System.out.println("Enter a character to continue");
iChar = System.in.read();
System.out.println("Char entered was : " + (char)iChar);
}
catch(IOException e)
{
System.out.println("Error while reading : " + e);
}
}
}
27. 1.12.1 Java Keywords:
• The following list shows the reserved words in Java.
• These reserved words may not be used as constant or variable or any other identifier names.
27
abstract assert boolean break
byte case catch char
class const continue default
do double else enum
extends final finally float
for goto if implements
import instanceof int interface
long native new package
private protected public return
short static strictfp super
switch synchronized this throw
throws transient try void
volatile while
28. 1.12.2 Java Identifiers:
• All Java components require names.
• Names used for classes, variables and methods are called identifiers.
• In Java, there are several points to remember about identifiers.
• They are as follows:
➢ All identifiers should begin with a letter (A to Z or a to z), currency character ($)
or an underscore (_).
➢ After the first character identifiers can have any combination of characters.
➢ A key word cannot be used as an identifier.
➢ Most importantly identifiers are case sensitive.
❖ Examples of legal identifiers: age, $salary, _value, __1_value
❖ Examples of illegal identifiers: 123abc, -salary 28
29. 1.12.3 Java Modifiers:
• Like other languages, it is possible to modify classes, methods, etc., by using
modifiers.
• There are two categories of modifiers:
1) Access Modifiers: default, public , protected, private
2) Non-access Modifiers: final, abstract, strictfp
29
30. 1.2.4 Variable and Datatype in Java
• Variable is a name of memory location.
• There are three types of variables:
1) local,
2) instance and
3) static.
• There are two types of datatypes in java,
I. primitive and
II. non-primitive.
30
32. 1.2.4.2 Types of Variable
• There are three types of variables in java
1) local variable
2) instance variable
3) static variable
1) Local Variable
• A variable that is declared inside the method is called local variable.
2) Instance Variable
• A variable that is declared inside the class but outside the method is called instance
variable .
• It is not declared as static.
3) Static variable
• A variable that is declared as static is called static variable.
• It cannot be local.
32
33. 1.2.4.3 Example to understand the types of variables
33
class A
{
int data=50;//instance variable
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
}//end of class
34. 1.2.4.4 Data Types in Java
• In java, there are two types of data types
1) primitive data types
2) non-primitive data types
34
35. 1.2.4.4 Data Types in Java …
35
Data Type Default Value Default size
boolean false 1 bit
char 'u0000' 2 byte
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
float 0.0f 4 byte
double 0.0d 8 byte
• Why char uses 2 byte in java and what is u0000 ?
➢ Because java uses unicode system rather than ASCII code system.
➢ u0000 is the lowest range of unicode system
36. 1.2.4.5 Unicode System
• Unicode is a universal international standard character encoding that is capable of
representing most of the world's written languages.
➢ Why java uses Unicode System?
• Before Unicode, there were many language standards:
▪ ASCII (American Standard Code for Information Interchange) for the United States.
▪ ISO 8859-1 for Western European Language.
▪ KOI-8 for Russian.
▪ GB18030 and BIG-5 for Chinese, and so on.
➢ This caused two problems:
▪ A particular code value corresponds to different letters in the various language standards.
▪ The encodings for languages with large character sets have variable length.
▪ Some common characters are encoded as single bytes, other require two or more byte.
▪ To solve these problems, a new language standard was developed i.e. Unicode System.
▪ In unicode, character holds 2 byte, so java also uses 2 byte for characters.
▪ lowest value:u0000
▪ highest value:uFFFF
36
38. 1.2.6 Operators : Java instanceof
• The java instanceof operator is used to test whether the object is an instance of the
specified type (class or subclass or interface).
• The instanceof in java is also known as type comparison operator because it
compares the instance with type. It returns either true or false.
• If we apply the instanceof operator with any variable that has null value, it returns false.
Example: The simple example of instance operator where it tests the current class.
38
class Simple1
{
public static void main(String args[])
{
Simple1 s=new Simple1();
System.out.println(s instanceof Simple); //true
}
}