Chapter 1 Introduction To Java and Elementary Programming
Chapter 1 Introduction To Java and Elementary Programming
You can also use IDE like Eclipse to run the java
program but we will cover that part later in the
coming tutorials. For the sake of simplicity, I will only
use text editor and command prompt (or terminal).
Step 2: Save the file as FirstJavaProgram.java. You may be wondering why we have
named the file as FirstJavaProgram, the thing is that we should always name the file same
as the public class name. In our program, the public class name is FirstJavaProgram, that’s
why our file name should be FirstJavaProgram.jav
Step 3: In this step, we will compile the program. For this, open command prompt (cmd)
on Windows, if you are Mac OS then open Terminal.
CONCEPT OF BYTECODE AND JVM
What is JVM?
Java virtual Machine (JVM) is a virtual Machine that provides runtime environment to
execute java byte code.
The JVM doesn't understand Java typo, that's why you compile your *.java files to obtain
*.class files that contain the bytecodes understandable by the JVM.
1. syntax error
2. runtime errors
3. logic errors
1. Syntax Errors
Errors that are detected by the compiler are called syntax errors or compile errors. Syntax errors result from errors
in code construction, such as mistyping a keyword, omitting some necessary punctuation, or using an opening brace
without a corresponding closing brace.
These errors are usually easy to detect because the compiler tells you where they are and what caused them. For
example, the following program has a syntax error:
public class JavaDemo {
}
2. Runtime Errors
Runtime errors are errors that cause a program to terminate abnormally. They occur while a program
is running if the environment detects an operation that is impossible to carry out. Input mistakes
typically cause runtime errors. An input error occurs when the program is waiting for the user to enter
a value, but the user enters a value that the program cannot handle.
For instance, if the program expects to read in a number, but instead the user enters a string, this
causes data-type errors to occur in the program.
Another example of runtime errors is division by zero. This happens when the divisor is zero for
integer divisions. For instance, the following program would cause a runtime error:
public class JavaDemo {
System.out.println(10/0);
Output:
at com.javaguides.JavaDemo.main(JavaDemo.java:24)
Logic Errors
Logic errors occur when a program does not perform the way it was intended to. Errors of this kind occur for many
different reasons. For example, suppose you wrote the program to convert Celsius 35 degrees to a Fahrenheit degree:
System.out.println((9 / 5) * 35 + 32);
}
Output:
67
You will get Fahrenheit 67 degrees, which is wrong. It should be 95.0. In Java, the division for integers is the
quotient—the fractional part is truncated—so in Java 9 / 5 is 1. To get the correct result, you need to use 9.0 / 5,
which results in 1.8.
Common Errors
Missing a closing brace, missing a semicolon, missing quotation marks for strings, and misspelling names are
common errors for new programmers.
IDENTIFIER AND VARIABLES
public class Test
int a = 20;
}
In the above java code, we have 5 identifiers namely :
● Test : class name.
● main : method name.
● String : predefined class name.
● args : variable name.
● a : variable name.
There are certain rules for defining a valid java identifier. These rules must be followed, otherwise we get compile-time error. These
rules are also valid for other languages like C,C++.
● The only allowed characters for identifiers are all alphanumeric characters([A-Z],[a-z],[0-9]), ‘$‘(dollar sign) and ‘_‘
(underscore).For example “geek@” is not a valid java identifier as it contain ‘@’ special character.
● Identifiers should not start with digits([0-9]). For example “123geeks” is a not a valid java identifier.
● Java identifiers are case-sensitive.
● There is no limit on the length of the identifier but it is advisable to use an optimum length of 4 – 15 letters only.
● Reserved Words can’t be used as an identifier. For example “int while = 20;” is an invalid statement as while is a
reserved word. There are 53 reserved words in Java.
MyVariable
MYVARIABLE
myvariable
i
Examples of invalid identifiers :
i
My Variable // contains a space
x1
123geeks // Begins with a digit
i1
a+c // plus sign is not an alphanumeric character
_myvariable
variable-2 // hyphen is not an alphanumeric character
$myvariable
sum_&_difference // ampersand is not an
sum_of_array
alphanumeric character
geeks123
VARIABLES IN JAVA
Variable is name of reserved area allocated in memory. In other words, it is a name of memory location. It is a
combination of "vary + able" that means its value can be changed.
Types of Variables
● local variable
● instance variable
● static variable
1) Local Variable
A variable declared inside the body of the method is called local variable. You can use this variable only within that method and the
other methods in the class aren't even aware that the variable exists.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is called instance variable. It is not declared as static.
It is called instance variable because its value is instance specific and is not shared among instances.
3) Static variable
A variable which is declared as static is called static variable. It cannot be local. You can create a single copy of static variable and share
among all the instances of the class. Memory allocation for static variable happens only once when the class is loaded in the memory.
Example to understand the types of variables in java
1. class A{
2. int data=50;//instance variable
3. static int m=100;//static variable
4. void method(){
5. int n=90;//local variable
6. }
7. }//end of class
DATA TYPES
Data types specify the different sizes and values that can be stored in the variable. There are two types
of data types in Java:
1. Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float
and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and
Arrays.
Java Primitive Data Types
In Java language, primitive data types are the building blocks of data manipulation. These are the most
basic data types available in Java language.
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
The Boolean data type specifies one bit of information, but its "size" can't be defined precisely.
The byte data type is used to save memory in large arrays where the memory savings is most required.
It saves space because a byte is 4 times smaller than an integer. It can also be used in place of "int"
data type.
The short data type can also be used to save memory just like byte data type. A short data type is 2
times smaller than an integer.
The int data type is generally used as a default data type for integral values unless if there is no
problem about memory.
the variable value directly in memory. They are strings, objects, arrays, etc.
String: Strings are defined as an array of characters. The difference between a character array and a string is the
string is terminated with a special character ‘\0’.
Below is the basic syntax for declaring a string in Java programming language.
Syntax:
<String_Type> <string_variable> = “<sequence_of_string>”;
Example:
// Declare String without using new operator
String s = "GeeksforGeeks";
1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
Arithmetic Operators: They are used to perform simple arithmetic operations on primitive data types.
● * : Multiplication
● / : Division
● % : Modulo
● + : Addition
● – : Subtraction
❖ Unary Operators: Unary operators need only one operand. They are used to increment, decrement or negate a
value.
❖ – :Unary minus, used for negating the values.
❖ + :Unary plus, used for giving positive values. Only used when deliberately converting a negative value
to positive.
❖ ++ :Increment operator, used for incrementing the value by 1. There are two varieties of increment
operator.
➢ Post-Increment : Value is first used for computing the result and then incremented.
➢ Pre-Increment : Value is incremented first and then result is computed.
❖ — : Decrement operator, used for decrementing the value by 1. There are two varieties of decrement
operator.
➢ Post-decrement : Value is first used for computing the result and then decremented.
➢ Pre-Decrement : Value is decremented first and then result is computed.
❖ ! : Logical not operator, used for inverting a boolean value.
PRECEDENCE AND ASSOCIATIVITY OF OPERATORS
Precedence and associative rules are used when dealing with hybrid equations involving more than
one type of operator. In such cases, these rules determine which part of the equation to consider first
as there can be many different valuations for the same equation. The below table depicts the
precedence of operators in decreasing order as magnitude with the top representing the highest
Example
System.out.println(myInt); // Outputs 9
System.out.println(myDouble); // Outputs 9.0
}
NARROWING CASTING
Narrowing casting must be done manually by placing the type in parentheses in front of the value:
Example