Java M1
Java M1
JDK in Java
The Java Development Kit (JDK) is a cross-platformed
software development environment that offers a collection
of tools and libraries necessary for developing Java-based JDK=JRE+Development Tools
software applications and applets. It is a core package used
in Java, along with the JVM (Java Virtual Machine) and the
JRE (Java Runtime Environment).
if you are only interested in running Java programs on your machine then you can easily do it using Java Runtime
Environment. However, if you would like to develop a Java-based software application then along with JRE you
may need some additional necessary tools, which is called JDK.
The JDK has a private Java Virtual Machine (JVM) and a few other resources necessary for the development of a
Java Application.
JDK contains:
•Java Runtime Environment (JRE),
•An interpreter/loader (Java),
•A compiler (javac),
•An archiver (jar) and many more.
1. JDK (Java Development Kit) is a Kit that provides the environment to develop and execute(run) the Java
program. JDK is a kit(or package) that includes two things
•Development Tools(to provide an environment to develop your java programs)
•JRE (to execute your java program).
2. JRE (Java Runtime Environment) is an installation package that provides an environment to only run(not
develop) the java program(or application)onto your machine. JRE is only used by those who only want to run Java
programs that are end-users of your system.
3. JVM (Java Virtual Machine) is a very important part of both JDK and JRE because it is contained or inbuilt in
both. Whatever Java program you run using JRE or JDK goes into JVM and JVM is responsible for executing the
java program line by line, hence it is also known as an interpreter.
BRIDGE
Increases performance
by using reused codes
affects performance by
line by line
interpretation
Java language features
•Simple: Java was designed with a small number of language constructs so that programmers
could learn it quickly. It eliminates several language features available in C/C++ that are
associated with poor programming practices or rarely used
•Object Oriented: In java everything is Object which has some data and behaviour. Java can be
easily extended as it is based on Object Model.
•Distributed; Java is designed to support various levels of network connectivity. Java
applications are network aware: TCP/IP support is built into Java class libraries. They can open
and access remote objects on the Internet.
•Interpreted: Java is compiled to bytecodes, which are interpreted by a Java run-time
environment.
•Robust: Java is designed to eliminate certain types of programming errors. Java is strongly
typed, which allows extensive compile-time error checking. It does not support memory
pointers, which eliminates the possibility of overwriting memory and corrupting data. In
addition, its automatic memory management (garbage collection) eliminates memory leaks and
other problems associated with dynamic memory allocation/de-allocation.
Java language features
•Secure: Java is designed to be secure in a networked environment. The Java run-time
environment uses a bytecode verification process to ensure that code loaded over the network
does not violate Java security constraints.
•Architecture Neutral: Java applications that are compiled to bytecodes can be interpreted by
any system that implements the Java Virtual Machine. Since the Java Virtual Machine is
supported across most operating systems, this means that Java applications are able to run on
most platforms.
•Portable: In addition to supporting architecture neutrality, Java ensures that other
implementation-dependent aspects of language specification are eliminated. For example, Java
specifies the sizes of primitive data types and their arithmetic behavior.
•High Performance: Although Java is an interpreted language, it was designed to support “just-
in-time” compilers, which dynamically compile bytecodes to machine code.
•Multithreaded: Java supports multiple threads of execution (a.k.a., lightweight processes),
including a set of synchronization primitives. This makes programming with threads much easier.
•Dynamic Language: Java supports dynamic loading of classes (a.k.a. “load on demand”),
dynamic compilation, and automatic memory management (garbage collection)
Secured
Java is best known for its security. With Java, we can develop virus-free
systems. Java is secured because:
•No explicit pointer
•Java Programs run inside a virtual machine sandbox
Architecture-neutral
Java is architecture neutral because there are no implementation dependent features, for example, the size of primitive
types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes of memory for 64-bit
architecture. However, it occupies 4 bytes of memory for both 32 and 64-bit architectures in Java.
Difference Between C, C++ and Java
Difference Between C, C++ and Java
Hello Java Program
class Simple
{
public static void main(String args[])
{
System.out.println("Hello Java"); Save the above file as Simple.java.
}
} To compile:
javac Simple.java
To execute:
java Simple
Output:
Hello Java
Parameters used in First Java Program
•class keyword is used to declare a class in Java.
•public keyword is an access modifier that represents visibility. It means it is visible to
all.
•static is a keyword. If we declare any method as static, it is known as the static
method. The core advantage of the static method is that there is no need to create an
object to invoke the static method. The main() method is executed by the JVM, so it
doesn't require creating an 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 the starting point of the program.
•String[] args or String args[] is used for command line argument.
•System.out.println() is used to print statement. Here, System is a class, out is an
object of the PrintStream class, println() is a method of the PrintStream class.
There is no classical nextChar() method in Java Scanner class. The best and most simple alternative to taking char
input in Java would be the next().charAt(0). The charAt(0) command is used in combination with the simple next()
command which instructs Java to record the next character or string that is input into the command line. This input
can be a string, character, or numeral. The charAt command is a way to filter the unwanted data types and only
restricts the input to char data type. Since charAt only returns output in the form of a char value, it converts any
type of data type to a char type.
Security
The String is widely used in Java applications to store sensitive pieces of information like usernames, passwords, connection URLs, network connections,
etc. Hence securing String class is crucial regarding the security of the whole application in general
Synchronization
Being immutable automatically makes the String thread safe since they won’t be changed when accessed from multiple threads.
Hashcode Caching
String objects are also widely used in hash implementations like HashMap, HashTable, HashSet, etc. The immutability guarantees Strings that their value
won’t change.
Performance
String pool exists because Strings are immutable. In turn, it enhances the performance by saving heap memory and faster access of hash implementations
when operated with Strings.
Operators in Java
Java provides many types of operators which can be used according to the need. They are classified based on the
functionality they provide.
What are the Java Operators?
Operators in Java are the symbols used for performing specific operations in Java. Operators make tasks like
addition, multiplication, etc
}
}
Java Unary Operator
The Java unary operators require only one operand. Unary operators are used to perform
various operations (Post Increment(a++) and Pre Increment(--a)
Java Unary Operator Example: ++ and --
public class OperatorExample{
public static void main(String args[]){
int x=10;
System.out.println(x++);//10 (11)
System.out.println(++x);//12
System.out.println(x--);//12 (11)
System.out.println(--x);//10
}
}
Output:
10
12
12
10
Java Assignment Operators
Assignment operators are used to assign values to variables.
Java Comparison Operators
Comparison operators are used to compare two values (or variables). This is important in programming, because it helps us to
find answers and make decisions.
The return value of a comparison is either true or false. These values are known as Boolean values,
Java Logical Operators
You can also test for true or false values with logical operators.
Logical operators are used to determine the logic between variables or values:
Ternary Operator in Java
Java ternary operator is the only conditional operator that takes three operands. It’s a one-liner replacement for the
if-then-else statement and is used a lot in Java programming. We can use the ternary operator in place of if-else
conditions or even switch conditions using nested ternary operators. Although it follows the same algorithm as of
if-else statement, the conditional operator takes less space and helps to write the if-else statements in the shortest
way possible.
Syntax:
variable = Expression1 ? Expression2: Expression3
if(Expression1)
{
variable = Expression2;
}
else
{
variable = Expression3;
}
class Ternary {
public static void main(String[] args)
{
1. Bitwise OR (|)
This operator is a binary operator, denoted by ‘|’. It returns bit
by bit OR of input values, i.e., if either of the bits is 1, it gives 1,
else it shows 0.
Example:
Example:
Example:
This operator is a unary operator, denoted by ‘~.’ It returns the one’s complement
representation of the input value, i.e., with all bits inverted, which means it makes every 0 to
1, and every 1 to 0.
Example:
~ 0101
________
1010 = 10 (In decimal)
Note: Compiler will give 2’s complement of that number, i.e., 2’s complement of 10 will be -6.
public class operators {
public static void main(String[] args)
{
int a = 5;
int b = 7;
System.out.println("a&b = " + (a & b));
System.out.println("a|b = " + (a | b));
System.out.println("a^b = " + (a ^ b));
System.out.println("~a = " + ~a);
a &= b;
System.out.println("a= " + a);
}
}
Java Control Statements
In java, the default execution flow of a program is a sequential order. But the sequential order of execution
flow may not be suitable for all situations. Sometimes, we may want to jump from line to another line, we may
want to skip a part of the program, or sometimes we may want to execute a part of the program again and
again. To solve this problem, java provides control statements.
Java Selection Statements
In java, the selection statements are also known as decision making statements or branching statements or
conditional control statements. The selection statements are used to select a part of the program to be
executed based on a condition. Java provides the following selection statements.
•if statement
•if-else statement
•nested if statement
•if-else if statement
•switch statement
if statement in java
In java, we use the if statement to test a condition and decide the execution of a block of statements based on
that condition result. The if statement checks, the given condition then decides the execution of a block of
statements. If the condition is True, then the block of statements is executed and if it is False, then the block of
statements is ignored. The syntax and execution flow of if the statement is as follows.
import java.util.Scanner;
}
if-else statement in java
In java, we use the if-else statement to test a condition and pick the execution of a block of statements out of two blocks
based on that condition result. The if-else statement checks the given condition then decides which block of statements to be
executed based on the condition result. If the condition is True, then the true block of statements is executed and if it is False,
then the false block of statements is executed. The syntax and execution flow of if-else statement is as follows.
import java.util.Scanner;
public class IfElseStatementTest {
}
Nested if statement in java
Writing an if statement inside another if-statement is called nested if statement. The general syntax of the nested
if-statement is as follows.
import java.util.Scanner;
public class NestedIfStatementTest {
public static void main(String[] args) {
}
}
Java if-else-if ladder Statement
The if-else-if ladder statement executes one condition from multiple statements.
Syntax:
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}
public class IfElseIfExample {
//Java Program to demonstrate the use public static void main(String[] args) {
of If else-if ladder. int marks=65;
if(marks<50){
//It is a program of grading system for System.out.println("fail");
fail, D grade, C grade, B grade, A grade }
and A+. else if(marks>=50 && marks<60){
System.out.println("D grade");
}
else if(marks>=60 && marks<70){
System.out.println("C grade");
}
else if(marks>=70 && marks<80){
System.out.println("B grade");
}
else if(marks>=80 && marks<90){
System.out.println("A grade");
}else if(marks>=90 && marks<100){
System.out.println("A+ grade");
}else{
System.out.println("Invalid!");
}
}
}
import java.util.Scanner;
public class IfElseIfStatementTest {
public static void main(String[] args) {
int num1, num2, num3;
Scanner read = new Scanner(System.in);
System.out.print("Enter any three numbers: ");
num1 = read.nextInt();
num2 = read.nextInt();
num3 = read.nextInt();
else
System.out.println("\nThe largest number is " + num3) ;
}
}
switch statement in java
Using the switch statement, one can select only one option from more
number of options very easily. In the switch statement, we provide a
value that is to be compared with a value associated with each option.
Whenever the given value matches the value associated with an option,
the execution starts from that option. In the switch statement, every
option is defined as a case.
The switch statement has the following syntax and execution flow
diagram.
Check whether an alphabet is vowel or consonant using if..else statement
import java.util.Scanner;
public class Vowelif {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
System.out.print("Enter any Alphabet: ");
char ch = read.next().charAt(0);
}
}
import java.util.Scanner;
public class Vowel{
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
System.out.print("Enter any Alphabet: ");
char ch = read.next().charAt(0);
switch(ch)
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
while statement
do-while statement
for statement
for-each statement
for statement in java
In Java, for loop is similar to C and C++. It enables us to initialize the loop variable, check the condition, and
increment/decrement in a single line of code. We use the for loop only when we exactly know the number
of times, we want to execute the block of code.
int num = 1;
}
}
Java do-while loop
The do-while loop checks the condition at the end of the loop after executing the loop
statements. When the number of iteration is not known and we have to execute the loop at
least once, we can use do-while loop.
It is also known as the exit-controlled loop since the condition is not checked in advance. The
syntax of the do-while loop is given below.
do
{
//statements
} while (condition);
The flow chart of the do-while loop is given in the following image.
public class Calculation {
public static void main(String[] args) {
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
do {
System.out.println(i);
i = i + 2;
}while(i<=10);
}
}
Jump Statements
Jump statements are used to transfer the control of the program to the specific statements. In
other words, jump statements transfer the execution control to the other part of the program.
There are two types of jump statements in Java, i.e., break and continue.
Java break statement
As the name suggests, the break statement is used to break the current flow of the program
and transfer the control to the next statement outside a loop or switch statement. However, it
breaks only the inner loop in the case of the nested loop.
The break statement cannot be used independently in the Java program, i.e., it can only be
written inside the loop or switch statement.
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
}
System.out.println(i);
}
}
}
Java continue statement
Unlike break statement, the continue statement doesn't break the loop,
whereas, it skips the specific part of the loop and jumps to the next iteration of
the loop immediately.
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
System.out.println(i);
}
}
}
Return Statement
Return statements are the jump statements used inside methods (or functions) only. Any code in the method which is written
after the return statement might be treated as unreachable by the compiler.
Then return statement terminates the execution of the current method and passes the control to the calling method.
Syntax:
return value;
Syntax:
return;
Example 1: Void Method In a method that doesn't return a value, you can
simply use return; to exit early.
class Break_statement {
public static void main(String[] args) {
int age = 12;
System.out.println("Using Return");
if (age<18)
return; //terminates the method
System.out.println("Will not get executed!");
}
}
Example 2: Returning a Value
In a method that returns a value, you specify the type of value you want to return.