Java Module1
Java Module1
To create a simple Java program, you need to create a class that contains
the main method. Let's understand the requirement first.
o Install the JDK if you don't have installed it, download the JDK and install it.
o Set path of the jdk/bin directory. http://www.javatpoint.com/how-to-set-
path-in-java
o Create the Java program
o Compile and run the Java program
1. class Simple{
2. public static void main(String args[]){
3. System.out.println("Hello Java");
4. }
5. }
Save the above file as Simple.java
To
compile: javac Simple.java
To
java Simple
execute:
Output:
Hello Java
Compilation Flow:
When we compile Java program using javac tool, the Java compiler
converts the source code into byte code.
Syntax Error:
Syntax and Logical errors are faced by Programmers.
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.
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.
Example:
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.
Example:
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.
Example:
Example:
Example:
Example:
1. float f1 = 234.5f
Literals in Java
In Java, literal is a notation that represents a fixed value in the source
code. In lexical analysis, literals of a given type are generally known
as tokens. In this section, we will discuss the term literals in Java.
Literals
In Java, literals are the constant values that appear directly in the
program. It can be assigned directly to a variable. Java has various types
of literals. The following figure represents a literal.
Types of Literals in Java
There are the majorly four types of literals in Java:
1. Integer Literal
2. Character Literal
3. Boolean Literal
4. String Literal
Integer Literals
Integer literals are sequences of digits. There are three types of integer
literals:
o Decimal Integer: These are the set of numbers that consist of digits from
0 to 9. It may have a positive (+) or negative (-) Note that between
numbers commas and non-digit characters are not permitted. For
example, 5678, +657, -89, etc.
Backslash Literals
Java supports some special backslash character literals known as
backslash literals. They are used in formatted output. For example:
Character Literals
A character literal is expressed as a character or an escape sequence,
enclosed in a single quote ('') mark. It is always a type of char. For
example, 'a', '%', '\u000d', etc.
String Literals
String literal is a sequence of characters that is enclosed
between double quotes ("") marks. It may be alphabet, numbers, special
characters, blank space, etc. For example, "Jack", "12345", "\n", etc.
Example:
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
}
}
Output
101
64
64206
15
Let's look at how to save the file, compile, and run the program. Please
follow the subsequent steps –
Open notepad and add the code as above.
Output
C:\> javac MyFirstJavaProgram.java
C:\> java MyFirstJavaProgram
Hello World
Scope of a Variable
In programming, a variable can be declared and defined inside a class,
method, or block. It defines the scope of the variable i.e. the visibility or
accessibility of a variable. Variable declared inside a block or method are
not visible to outside. If we try to do so, we will get a compilation error.
Note that the scope of a variable can be nested.
private No No No
default Yes No No
Syntax:
There are many types of operators in Java which are given below:
o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.
Arithmetic multiplicative * / %
additive + -
equality == !=
bitwise exclusive OR ^
bitwise inclusive OR |
logical OR ||
Output:
10
12
12
10
Output:
22
21
Output:
15
5
50
2
0
Logical operators
Logical operators are used to performing logical “AND”, “OR” and “NOT”
operations, i.e. the function similar to AND gate and OR gate in digital
electronics. They are used to combine two or more conditions/constraints or
to complement the evaluation of the original condition under particular
consideration. One thing to keep in mind is, while using AND operator, the
second condition is not evaluated if the first one is false. Whereas while
using OR operator, the second condition is not evaluated if the first one is
true, i.e. the AND and OR operators have a short-circuiting effect. Used
extensively to test for several conditions for making a decision.
1. AND Operator ( && ) – if( a && b ) [if true execute else don’t]
2. OR Operator ( || ) – if( a || b) [if one of them is true execute else
don’t]
3. NOT Operator ( ! ) – !(a<b) [returns false if a is smaller than b]
Example:
int x = 5;
}
}
Output:
true
import java.io.*;
class Logical {
public static void main(String[] args)
{
// initializing variables
int a = 10, b = 20, c = 20, d = 0;
// Displaying a, b, c
System.out.println("Var1 = " + a);
System.out.println("Var2 = " + b);
System.out.println("Var3 = " + c);
Output
Var1 = 10
Var2 = 20
Var3 = 20
The sum is: 50
Relational operator
// Main class
class GFG {
Output
Var1 = 5
Var2 = 10
Var3 = 5
var1 == var2: false
var1 == var3: true
int x = 10;
In the above statement, we use the assignment operator ( = ) to assign
the value 10 to x.
Shorthand Operators
Statements like this:
a = a + 10;
are used a lot in programs. Java provides shorthand operators to
combine the arithmetic and assignment operator into a single operator
and write the above statement like this:
a += 10;
Both these statements are equivalent. They add 10 to a and assign the
value back to a. The second statement uses the shorthand operator and
is a little simple and saves a bit of typing.
There are shorthand operators for all arithmetic binary operators. The
table below lists some of the shorthand operators in Java:
+= x += 5 x=x+5
-= x -= 5 x=x-5
*= x *= 5 x=x*5
/= x /= 5 x=x/5
%= x %= 5 x=x%5
x += 20; //Same as x = x + 20
y *= 3; //Same as y = y * 3
z -= 15; //Same as z = z - 15
X=30
Y=60
Z=15
boolean 1
byte 8 (1 byte)
char 16 (2 bytes)
int 32 (4 bytes)
long 64 (8 bytes)
float 32 (4 bytes)
double 64 (8 bytes)
Example:
Java
// Main class
class GFG {
Output
Int value 100
Long value 100
Float value 100.0
Java Type Casting
Type casting is when you assign a value of one primitive data type to another
type.
Widening Casting
Widening casting is done automatically when passing a smaller size type to a
larger size type:
Example
public class Main {
int myInt = 9;
System.out.println(myInt); // Outputs 9
output
9
9.0
Narrowing Casting
Narrowing casting must be done manually by placing the type in parentheses
in front of the value:
Example
public class Main {
System.out.println(myInt); // Outputs 9
output
9.78
9
Operator Precedence
What is operator precedence?
The operator precedence represents how two expressions are bind
together. In an expression, it determines the grouping of operators with
operands and decides how an expression will evaluate.
While solving an expression two things must be kept in mind the first is
a precedence and the second is associativity.
Precedence
Precedence is the priority for grouping different types of operators with
their operands. It is meaningful only if an expression has more than one
operator with higher or lower precedence. The operators having higher
precedence are evaluated first. If we want to evaluate lower precedence
operators first, we must group operands by using parentheses and then
evaluate.
Associativity
We must follow associativity if an expression has more than two operators
of the same precedence. In such a case, an expression can be solved
either left-to-right or right-to-left, accordingly.
1. 1 + 5 * 3
You might be thinking that the answer would be 18 but not so. Because
the multiplication (*) operator has higher precedence than the addition
(+) operator. Hence, the expression first evaluates 5*3 and then evaluates
the remaining expression i.e. 1+15. Therefore, the answer will be 16.
1. x + y * z / k
In the above expression, * and / operations are performed before +
because of precedence. y is multiplied by z before it is divided by k
because of associativity.
class Precedence {
public static void main(String[] args) {
System.out.println(result);
}
}
Output:
2
Expressions
An expression is a combination of operators, constants and variables. An expression
may consist of one or more operands, and zero or more operators to produce a value.
Types of Expressions:
Expressions may be of the following types:
class Main {
public static void main(String[] args) {
Output:
Hey Jude!
More Data Types and Operators
Java Arrays
Normally, an array is a collection of similar type of elements which has contiguous memory location.
Array in Java is index-based, the first element of the array is stored at the
0th index, 2nd element is stored on 1st index and so on.
Advantages
o Code Optimization: It makes the code optimized, we can retrieve or sort
the data efficiently.
o Random access: We can get any data located at an index position.
1. arrayRefVar=new datatype[size];
Output:
10
20
70
40
50
// and length()
+ array.length);
+ str.length());
Output
The size of the array is 4
The size of the String is 13
Output
3
Explanation: Here the str is an array of type string and that’s why str.length
is used to find its length.
The drawback of the enhanced for loop is that it cannot traverse the
elements in reverse order. Here, you do not have the option to skip any
element because it does not work on an index basis. Moreover, you
cannot traverse the odd or even elements only.
But, it is recommended to use the Java for-each loop for traversing the
elements of array and collection because it makes the code readable.
Advantages
o It makes the code more readable.
o It eliminates the possibility of programming errors.
Syntax
The syntax of Java for-each loop consists of data_type with the variable
followed by a colon (:), then array or collection.
How it works?
The Java for-each loop traverses the array or collection until the last
element. For each element, it stores the element in the variable and
executes the body of the for-each loop.
Output:
12
12
14
44
Let us see another of Java for-each loop where we are going to total the
elements.
1. class ForEachExample1{
2. public static void main(String args[]){
3. int arr[]={12,13,14,44};
4. int total=0;
5. for(int i:arr){
6. total=total+i;
7. }
8. System.out.println("Total: "+total);
9. }
10.}
Output:
Total: 83
Output:
vimal
sonoo
ratan
Strings
Java String
In Java, string is basically an object that represents sequence of char
values. An array of characters works same as Java string. For example:
1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);
is same as:
1. String s="javatpoint";
Java String class provides a lot of methods to perform operations on
strings such as compare(), concat(), equals(), split(), length(), replace(),
compareTo(), intern(), substring() etc.
CharSequence Interface
The CharSequence interface is used to represent the sequence of
characters. String, StringBuffer and StringBuilder classes implement it. It
means, we can create strings in Java by using these three classes.
We will discuss immutable string later. Let's first understand what String
in Java is and how to create the String object.
What is String in Java?
Generally, String is a sequence of characters. But in Java, string is an
object that represents a sequence of characters. The java.lang.String class
is used to create a string object.
1. By string literal
2. By new keyword
1) String Literal
Java String literal is created by using double quotes. For Example:
1. String s="welcome";
Each time you create a string literal, the JVM checks the "string constant
pool" first. If the string already exists in the pool, a reference to the
pooled instance is returned. If the string doesn't exist in the pool, a new
string instance is created and placed in the pool. For example:
1. String s1="Welcome";
2. String s2="Welcome";//It doesn't create a new instance
In the above example, only one object will be created. Firstly, JVM will not
find any string object with the value "Welcome" in string constant pool
that is why it will create a new object. After that it will find the string with
the value "Welcome" in the pool, it will not create a new object but will
return the reference to the same instance.
By new keyword
1. String s=new String("Welcome");//creates two objects and one refer
ence variable
In such case, JVM will create a new string object in normal (non-pool) heap
memory, and the literal "Welcome" will be placed in the string constant
pool. The variable s will refer to the object in a heap (non-pool).
class StringReverseExample{
public static void main(String[] args) {
String string = "abcdef";
String reverse = new StringBuffer(string).reverse().toString();
System.out.println("\nString before reverse: "+string);
System.out.println("String after reverse: "+reverse);
}
}
Result
The above code sample will produce the following result.
String before reverse: abcdef
String after reverse: fedcba
StringExample.java
Output:
java
strings
example
Bitwise Operators
Bitwise Operators
~ 0101
________
1010 = 10 (In decimal)
AND Operator
Output
9
OR operator
Output
31
class BitwiseAndOperator {
public static void main(String[] args){
int A = 10;
int B = 3;
int Y;
Y = A & B;
System.out.println(Y);
}
}
Output
Bitwise OR Operator
class BitwiseOrOperator {
public static void main(String[] args){
int A = 10;
int B = 3;
int Y;
Y = A | B;
System.out.println(Y);
}
}
Output
11
class BitwiseXOROperator {
public static void main(String[] args){
int A = 10;
int B = 3;
int Y;
Y = A ^ B;
System.out.println(Y);
}
}
Output
class BitwiseComplementOperator {
public static void main(String[] args){
int A = 10;
int Y;
Y = ~A ;
System.out.println(Y);
}
}
Output
-11