Java Reference Guide: Steps To Download Java

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 28

Java Reference Guide

Steps to download Java


1. Verify if already Installed
Go to CMD and type: javac or javac --version
If not installed continue with next steps.
2. Download JDK from Oracle.com JAVA SE 11 or JAVA 8
3. Install JDK
4. Set Java Path
a. Right click on "this PC" and select Properties
b. Click on "Advanced system settings"
c. Click on Environment Variables
d. New User Variable
e. Variable: JAVA_HOME Value: Path to bin folder of Java Installation directory
5. Recheck if installation completed. Go to CMD and type: javac or javac --version

What is meant by Platform Independent Programming Language?


Platform independence means that execution of your program does not dependent on
type of operating system. It could be any : Linux, windows, Mac, etc. So compile code only
once and run it on any System.
What are the features of Java?
1. Portable – Write Once, Run Anywhere (WORA). Being architecture-neutral and having no
implementation dependent aspects of the specification makes Java portable.

2. Platform Independent. Unlike many other programming languages including C and C++,
when Java is compiled, it is not compiled into platform specific machine, rather into
platform-independent byte code.

3. Security is very well thought. Java's secure feature it enables to develop virus-free,
tamper-free systems.

4. Robust Memory Management. Java is robust because: It uses strong memory


management. There is a lack of pointers that avoids security problems. There is automatic
garbage collection in java which runs on the Java Virtual Machine to get rid of objects
which are not being used by a Java application anymore.

5. Multi-threaded. Multiple simultaneous tasks can be run simultaneously.


6. Dynamic and extensible. Dynamic because classes stored in separate files and loaded only
when needed. Extensible means it has many in-built libraries to support. Java is considered
to be more dynamic than C or C++ since it is designed to adapt to an evolving environment.
Java programs can carry an extensive amount of run-time information that can be used to
verify and resolve accesses to objects at run-time.

What is JRE?
The Java Runtime Environment, or JRE, is a software layer that runs on top of a computer’s
operating system software and provides the class libraries and other resources that a
specific Java program needs to run. It includes the JRE and other files and libraries required to
support any Java program.

What is JVM?

Java Virtual Machine (JVM) is a engine that provides runtime environment to drive the
Java Code or applications. It converts Java bytecode into machines language. JVM is a part of
Java Run Environment (JRE). In other programming languages, the compiler produces machine
code for a particular system. However, Java compiler produces code for a Virtual Machine
known as Java Virtual Machine.

First, Java code is complied into bytecode. This bytecode gets interpreted on different
machines.
What is JDK?
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software development
environment which is used to develop java applications and applets. It physically exists. It contains JRE +
development tools.
The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an
interpreter/loader (Java), a compiler (javac), an archiver (jar), a documentation generator (Javadoc) etc. to
complete the development of a Java Application.

What is Java Byte Code?


Java bytecode is the instruction set for the Java Virtual Machine. When we write a program in Java,
firstly, the compiler compiles that program and a bytecode is generated for that piece of code. When we
wish to run this .class file on any other platform, we can do so. After the first compilation, the bytecode
generated is now run by the Java Virtual Machine. A point to keep in mind is that bytecodes are non-
runnable codes and rely on the availability of an interpreter to execute and thus the JVM comes into play.
Java Byte code is used to achieve Platform Independence.
Why is Java called Interpreter Compiler language?
Java is called an Interpreter Compiler language because it uses both a compiler and an
interpreter. First, the Compiler compiles the Java code (.java) to the Java ByteCode (.class). The
Byte code once generated can be run anywhere. When we run the Bytecode, it is converted
to Machine language. And the program gives the expected output.

What is JIT?
When the JVM first starts up, thousands of methods are called. Compiling all of these
methods can significantly affect start-up time. The Just-In-Time (JIT) compiler is a component
of the runtime environment that improves the performance of Java applications by compiling
bytecodes to native machine code at run time.

What is the difference between JIT and Interpreter?

The difference is in how they generate the native code, how optimized it is as well how costly the
optimization is. Informally, an interpreter pretty much converts each byte-code instruction to
corresponding native instruction by looking up a predefined JVM-instruction to machine instruction
mapping (see below pic). Interestingly, a further speedup in execution can be achieved, if we take a
section of byte-code and convert it into machine code - because considering a whole logical section
often provides rooms for optimization as opposed to converting (interpreting) each line in isolation (to
machine instruction). This very act of converting a section of byte-code into (presumably optimized)
machine instruction is called compiling (in the current context). When the compilation is done at run-
time, the compiler is called JIT compiler.
A Sample Java Program

class MyFirstJava {
public static void main(String args[]) {
System.out.println(“Hello World”);
}
}

class MySecondJava {
public static void main (String args[]){
int age = 24;
System.out.println(“My age is”’+age);
}
}

class MyThirdJava {
public static void display(int age){
System.out.println("My age is "+age);
}
public static void main(String args[]) {
int age = 23;
age = age + 5;
display(age);
}
}
What are Access Modifiers in Java?

The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or
class. We can change the access level of fields, constructors, methods, and class by applying the
access modifier on it.

There are four types of Java access modifiers:

1. Private: The access level of a private modifier is only within the class. It cannot be accessed
from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.
3. Protected: The access level of a protected modifier is within the package and outside the
package through child class. If you do not make the child class, it cannot be accessed from
outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from within
the class, outside the class, within the package and outside the package.

Access Modifiers with Example


1. Private Access Modifier
class A{
private int x=40;
private void msg(){
System.out.println("Hello java");
System.out.println("Value of X is " + x);
}
}
public class Simple{
public static void main(String args[]){
A obj=new A();
System.out.println(obj.x);//Compile Time Error
obj.msg();//Compile Time Error
}
}
2. Default Access Modifier

package mypack1;
class A{
void msg(){
System.out.println("Hello");
}
}

package mypack2;
import mypack1.*;

class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}

3. Protected Access Modifier

package pack;
public class A{
protected void msg(){
System.out.println("Hello");
}
}

package mypack;
import pack.*;

class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
4. Public Access Modifier

package pack;
public class A{
public void msg(){
System.out.println("Hello");
}
}

package mypack;
import pack.*;

class B {
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}

What are class variable, instance variables and local variables in Java?

 Class variables − Class variables also known as sta c variables are declared with the sta c
keyword in a class, but outside a method, constructor or a block. There would only be one
copy of each class variable per class, regardless of how many objects are created from it.
 Instance variables − Instance variables are declared in a class, but outside a method. When
space is allocated for an object in the heap, a slot for each instance variable value is
created. Instance variables hold values that must be referenced by more than one method,
constructor or block, or essential parts of an object's state that must be present throughout
the class.
 Local variables − Local variables are declared in methods, constructors, or blocks. Local
variables are created when the method, constructor or block is entered and the variable
will be destroyed once it exits the method, constructor, or block.
public class VariableExample{
int myVariable; //instance variable
static int data = 30; //class variable

public static void main(String args[]){


int a = 100; //local variable
VariableExample obj = new VariableExample();

System.out.println("Value of instance variable myVariable"+obj.myVariable); //null


System.out.println("Value of static variable data: "+VariableExample.data);
System.out.println("Value of local variable a: "+a);
}

What is static variable in Java?


The static keyword in java is used for memory management mainly. We can apply java static
keyword with variables, methods, blocks and nested class. The static keyword belongs to the
class than instance of the class.

The static can be:

 variable (also known as class variable)


 method (also known as class method)
 block
 nested class
Example of Static Variable in Java

//Java Program to demonstrate the use of static variable


class Student{
int roll; //instance variable
String name;
static String college ="CGEC"; //static variable, class variable

Student(int r, String n){ //constructor


roll = r;
name = n;
}
//method to display the values
void display (){
System.out.println(roll + " " + name + " " + college);
}
}

//Test class to show the values of static variable


public class TestStaticVariable1{
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
s1.display();
s2.display();
}
}
Why is Final keyword used in Java?

The final keyword in java is used to restrict the user. The java final keyword can be used in many
context. Final can be:

1. variable (Value of Final variable is constant, you can not change it.)
2. method (You can’t override a Final method)
3. class (You can’t inherit from Final class)

The final keyword can be applied with the variables, a final variable that have no value it is called
blank final variable or uninitialized final variable. It can be initialized in the constructor only. The
blank final variable can be static also which will be initialized in the static block only.

class Bike{

final int speedlimit;//final variable =40

void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike obj=new Bike();
obj.run();
}
}

What is the Java main() method?

The main() is the starting point for JVM to start execution of a Java program. Without the main()
method, JVM will not execute the program. The syntax of the main() method is:
public: It is an access specifier. We should use a public keyword before the main() method so
that JVM can identify the execution point of the program. If we use private, protected, and
default before the main() method, it will not be visible to JVM.

static: You can make a method static by using the keyword static. We should call the main()
method without creating an object. Static methods are the method which invokes without
creating the objects, so we do not need any object to call the main() method.

void: In Java, every method has the return type. Void keyword acknowledges the compiler that
main() method does not return any value.

main(): It is a default signature which is predefined in the JVM. It is called by JVM to execute a
program line by line and end the execution after completion of this method. We can also
overload the main() method.

String args[]: The main() method also accepts some data from the user. It accepts a group of
strings, which is called a string array. It is used to hold the command line arguments in the form
of string values.

What happens if you remove static modifier from the main method?
Program compiles successfully . But at runtime throws an error “NoSuchMethodError”.

What happens if the main method is written without String args[]?

The program will compile, but not run, because JVM will not recognize the main() method.
Remember JVM always looks for the main() method with a string type array as a parameter.

Why is the main method always void?


As main() method doesn't return anything, its return type is void. As soon as
the main() method terminates, the java program terminates too. Hence, it doesn't make any
sense to return from main() method as JVM can't do anything with the return value of it.

What happens if the main method is made private?

The program will be compiled successfully but will throw a runtime error “Main Method not found
in Class”. The reason is JVM will not have access to the main method, so it cannot find the main
method to execute the program.
What are the Data Types used in Java?
Detailed explanation on primitive data types:

1. byte : The byte data type is an example of primitive data type. It is an 8-bit signed
two's complement integer. Its value-range lies between -128 to 127 (inclusive). The
byte data type is used to save memory in large arrays where the memory savings is
most required. It is 4 times small than integer.

2. short : The short data type is a 16-bit signed two's complement integer. Its value-
range lies between -32,768 to 32,767. 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.

3. Int: The int data type is a 32-bit signed two's complement integer. Its value-range
lies between (-231) to (231 -1). The int data type is generally used as a default data
type for integral values unless if there is no problem about memory.

4. long: The long data type is a 64-bit two's complement integer. Its value-range lies
between (-263) to (263 -1). The long data type is used when you need a range of
values more than those provided by int.

5. float: The float data type is a single-precision 32-bit IEEE 754 floating point. Its value
range is unlimited. It is recommended to use a float (instead of double) if you need
to save memory in large arrays of floating point numbers. The float data type should
never be used for precise values, such as currency. Its default value is 0.0F.

6. double: The double data type is a double-precision 64-bit IEEE 754 floating point.
Its value range is unlimited. The double data type is generally used for decimal
values just like float. The double data type also should never be used for precise
values, such as currency. Its default value is 0.0d.

7. char: The char data type is a single 16-bit Unicode character. Its value-range lies
between '\u0000' (or 0) to '\uffff' (or 65,535 inclusive).The char data type is used
to store characters.

8. boolean: The Boolean data type is used to store only two possible values: true
and false. This data type is used for simple flags that track true/false conditions.
The Boolean data type specifies one bit of information, but its "size" can't be
defined precisely
What are wrapper classes in Java?

The wrapper class in Java provides the mechanism to convert primitive into object and object into primitive.

What is the need of using Wrapper Classes in Java?

1. They convert primitive data types into objects. Objects are needed if we wish
to modify the arguments passed into a method (because primitive types are
passed by value).

2. The classes in java.util package handles only objects and hence wrapper classes
help in this case also.

3. Data structures in the Collection framework, such as ArrayList and Vector,


store only objects (reference types) and not primitive types.

4. An object is needed to support synchronization in multithreading.


What is Autoboxing?
Automatic conversion of primitive types to the object of their corresponding wrapper
classes is known as autoboxing. For example – conversion of int to Integer, long to Long, double
to Double etc.

What is Unboxing?
It is just the reverse process of autoboxing. Automatically converting an object of a
wrapper class to its corresponding primitive type is known as unboxing. For example –
conversion of Integer to int, Long to long, Double to double, etc.

Example of Autoboxing and Unboxing


A. Autoboxing

public class WrapperExample1{


public static void main(String args[]){

int a=20;
Integer i=Integer.valueOf(a); //converting int into Integer explicitly
Integer j=a; //autoboxing, now compiler will replace as Integer.valueOf(a)

System.out.println(a+" "+i+" "+j);


}
}

B. Unboxing

public class WrapperExample2{


public static void main(String args[]){
Integer a=new Integer(3);
int i=a.intValue();//converting Integer to int explicitly
int j=a;//unboxing, now compiler will write a.intValue() internally

System.out.println(a+" "+i+" "+j);


}
}
Operators used in Java
Java divides the operators into the following groups:

 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Bitwise operators
 Ternary Operator

Arithmetic Operators:

Arithmetic operators are used to perform common mathematical operations.

Assignment Operators:
Assignment operators are used to assign values to variables.
Logical Operators
Logical operators are used to determine the logic between variables or values

Comparison Operators
Comparison operators are used to compare two values:

Ternary Operator
The meaning of ternary is composed of three parts. The ternary
operator (? :) consists of three operands. It is used to evaluate Boolean
expressions. The operator decides which value will be assigned to the variable.
It is the only conditional operator that accepts three operands. It can be used
instead of the if-else statement. It makes the code much more easy, readable,
and shorter.
Example of Ternary Operator

public class TernaryOperatorExample {


public static void main(String args[]) {
int x, y;
x = 20;
y = (x == 1) ? 61: 90;
System.out.println("Value of y is: " + y); //90
y = (x == 20) ? 61: 90;
System.out.println("Value of y is: " + y); //61
}
}
Conditional Statements in Java

Java has the following conditional statements:

 Use if to specify a block of code to be executed, if a specified condition is true


 Use else to specify a block of code to be executed, if the same condition is false
 Use else if to specify a new condition to test, if the first condition is false
 Use switch to specify many alternative blocks of code to be executed

Syntax of If Else Statements

Syntax of Switch Case


Example If Else:

public class IfElseExample {


public static void main(String args[]) {

int time = 22;


if (time < 10) {
System.out.println("Good Morning ");
} else if (time < 20){
System.out.println("Good Day ");
}else{
System.out.println("Good Evening ");
}

}
}

Example Switch Case:

public class Main {


public static void main(String[] args) {
int day = 5;
switch (day) {
case 1:
System.out.println("Value is 1");
break;
case 2:
System.out.println("Value is 2");
break;
case 3:
System.out.println("Value is 3");
break;
default:
System.out.println("Out of Range");
break;
}
}
}
Iterations in Java
In programming languages, loops are used to execute a set of instructions/functions
repeatedly when some conditions become true. There are three types of loops in Java.

o for loop

o while loop

o do-while loop

Java For Loop


The Java for loop is used to iterate a part of the program several times. If the number of
iteration is fixed, it is recommended to use for loop.

There are three types of for loops in java.

o Simple For Loop


o For-each or Enhanced For Loop
o Labelled For Loop
a. Simple For Loop Example

public class ForExample {


public static void main(String[] args) {
for(int i=0; i<10; i++){
System.out.println(i);
}
}
}

b. Nested For Loop Example

public class NestedForExample {


public static void main(String[] args) {
for (int i=1; i<=3; i++) {
for (int j=1; j<=3; j++) {
System.out.println(i+" "+j);
}
}
}
}

c. Enhanced For Loop


public class ForEachExample {
public static void main(String[] args) {
int arr[] = {12,23,44,56,78};
for (int x : arr){
System.out.println(x);
}
}
}
public class enhancedforloop {
public static void main(String args[]) {
String array[] = {"Ron", "Harry", "Hermoine"};
//enhanced for loop
for (String x : array) {
System.out.println(x);
}
/* for loop for same function */
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
}
}

d. Labelled For Loop

public class LabeledForExample {


public static void main(String[] args) {

aa:
for(int i=1;i<=3;i++){
bb:
for (int j=1; j<=3; j++){
if(i==2 && j==2){
break aa;
}
System.out.println(i + " " + j);
}
}
}
}
Java While Loop
A while loop is a control flow statement that allows code to be executed repeatedly
based on a given Boolean condition. The while loop can be thought of as a repeating if
statement.

Example While Loop

class whileLoopDemo {
public static void main(String args[]) {
int x = 1;
// Exit when x becomes greater than 4
while (x <= 4) {
System.out.println("Value of x:" + x);
// Increment the value of x for
// next iteration
x++;
}
}
}
Java Do While Loop
Do while loop is similar to while loop with only difference that it checks for condition
after executing the statements, and therefore is an example of Exit Control Loop.

class dowhileloopDemo {
public static void main(String args[]) {
int x = 21;
do {
// The line will be printed even
// if the condition is false
System.out.println("Value of x:" + x);
x++;
} while (x < 20);
}
}
Arrays in Java
Java provides a data structure, the array, which stores a fixed-size sequential
collection of elements of the same type. An array is used to store a collection of data, but
it is often more useful to think of an array as a collection of variables of the same type.

Declaring an array:

double[] myList;
or
double myList[];

Creating an array:

myList = new double [arraySize];


or
double[] myList = {value0, value1, ..., valuek};

Example
double[] myList = new double[10];

or
double[] myList = {5, 8, 7, 9, 1, 2};
Processing of arrays

public class TestArray {


public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (int i = 0; i < myList.length; i++) {
System.out.println(myList[i] + " ");
}
// Summing all elements
double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
System.out.println("Total is " + total);
// Finding the largest element
double max = myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}
}

You might also like