JAVA
JAVA
JAVA
concise. It is based on C++ (so it is easier for programmers who know C++). Java
has removed many confusing and rarely-used features e.g. explicit pointers,
operator overloading etc. Java also takes care of memory management and it also
provides an automatic garbage collector. This collects the unused objects
automatically.
Java is a platform-independent language: The programs written in Java
language, after compilation, are converted into an intermediate level language
called the bytecode which is apart of the Java platform irrespective of the machine
on which the programs run. This makes java highly portable as its bytecodes can
be run on any machine by an interpreter called the Java Virtual Machine(JVM) and
thus java provides ‘reusability of code’.
Java is an object-oriented programming language: OOP makes the complete
program simpler by dividing it into a number of objects. The objects can be used as
a bridge to have data flow from one function to another. We can easily modify data
and function’s as per the requirements of the program.
Java is a robust language: Java programs must be reliable because they are
used in both consumer and mission-critical applications, ranging from Blu-ray
players to navigation systems.
Java is a multithreaded language: Java can perform many tasks at once by
defining multiple threads. For example, a program that manages a Graphical User
Interface (GUI) while waiting for input from a network connection uses another
thread to perform and wait’s instead of using the default GUI thread for both tasks.
This keeps the GUI responsive.
Java programs can create applets: Applets are programs that run in web
browsers.
Java does not require any preprocessor: It does not require inclusion of
header files for creating a Java application.
It is:
A specification where working of Java Virtual Machine is specified. But implementation
provider is independent to choose the algorithm. Its implementation has been provided by
Sun and other companies.
An implementation is a computer program that meets the requirements of the JVM
specification
Runtime Instance Whenever you write java command on the command prompt to run
the java class, an instance of JVM is created.
Difference betweem JDK, JRE and JVM
To understand the difference between these three, let us consider the following
diagram.
JDK – Java Development Kit (in short JDK) is Kit which provides the environment
to develop and execute(run) the Java program. JDK is a kit(or package) which includes
two things
1. Development Tools(to provide an environment to develop your java
programs)
2. JRE (to execute your java program).
Note : JDK is only used by Java Developers.
JRE – Java Runtime Environment (to say JRE) is an installation package which
provides environment to only run(not develop) the java program(or application)onto your
machine. JRE is only used by them who only wants to run the Java Programs i.e. end
users of your system.
JVM – Java Virtual machine(JVM) 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 interpreter.
class Main {
System.out.println("Hello");
Output:
Hello
Does JVM create an object of class Main?
The answer is “No”. We have studied that the reason for main() static in Java is to make
sure that the main() can be called without any instance. To justify the same, we can see
that the following program compiles and runs fine.
Microservices Introduction
A microservice is a small, loosely coupled distributed service. Microservice
Architectures evolved as a solution to the scalability and innovation challenges with
Monolith architectures (Monolith applications are typically huge – more 100, 000 line of
code). It allows you to take a large application and decompose or break into easily
manageable small components with narrowly defined responsibilities.
Reasons for using Microservice:
In monolith application, there are few challenges:
1. For a large application, it is difficult to understand the complexity and make code
changes fast and correctly, sometimes it becomes hard to manage the code.
2. Applications need extensive manual testing to ensure the impact of changes.
3. For small change, the whole application needs to be built and deployed.
4. The heavy application slows down start-up time.
Benefits of Microservices:
1. Small Modules –
Application is broken into smaller modules which are easy for developers to code
and maintain.
2. Easier Process Adaption –
By using microservices, new Technology & Process Adaption becomes easier. You
can try new technologies with the newer microservices that we use.
3. Independent scaling –
Each microservice can scale independently via X-axis scaling (cloning with more
CPU or memory) and Z-axis scaling (sharding), based upon their needs.
4. Unaffected –
Large applications remain largely unaffected by the failure of a single module.
5. DURS –
Each service can be independently DURS (deployed, updated, replaced, and
scaled).
Question : Can we have our class name as one of the predefined class name in our program?
Answer : Yes we can have it. However in the case of String class it will give runtime error.
Question : Can we have a variable name as one of the predefined class name in our program?
Answer : Yes we can have it.
Java Identifiers
In programming languages, identifiers are used for identification purpose. In Java, an
identifier can be a class name, method name, variable name or a label. For example :
public class Test
{
public static void main(String[] args)
{
int a = 20;
}
}
enum in Java
Enumerations serve the purpose of representing a group of named constants in a
programming language. For example the 4 suits in a deck of playing cards may be 4
enumerators named Club, Diamond, Heart, and Spade, belonging to an enumerated
type named Suit. Other examples include natural enumerated types (like the planets,
days of the week, colors, directions, etc.).
Enums are used when we know all possible values at compile time, such as choices
on a menu, rounding modes, command line flags, etc. It is not necessary that the set of
constants in an enum type stay fixed for all time.
In Java, we can also add variables, methods and constructors to it. The main objective
of enum is to define our own data types(Enumerated Data Types).
// Driver method
public static void main(String[] args)
{
Color c1 = Color.RED;
System.out.println(c1);
}
}
Output :
RED
First line inside enum should be list of constants and then other things like
methods, variables and constructor.
According to Java naming conventions, it is recommended that we name
constant with all capital letters
enum type can be passed as an argument to switch statement.
import java.util.Scanner;
// An Enum class
enum Day
// main().
Day day;
// Constructor
this.day = day;
switch (day)
case MONDAY:
case FRIDAY:
break;
case SATURDAY:
case SUNDAY:
break;
default:
break;
// Driver method
System.out.println(Day.valueOf(str));
t1.dayIsLike();
// java.lang.StringBuffer.appendCodePoint(int cp)
import java.lang.*;
sbf.appendCodePoint(65);
}
}
Default (no
modifier) Yes No No
private No No No
// System.out.println(x);
}
}
// filename: Test2.java
// this file
class Test2 {
t1.fun(5);
class Test1 {
void fun(int x) {
Output:
fun() called: x = 5
The Java program compiles and runs fine. Note that Test1 and fun() are not declared
before their use. Unlike C++, we don’t need forward declarations in Java. Identifiers
(class and method names) are recognized automatically from source files. Similarly,
library methods are directly read from the libraries, and there is no need to create
header files with declarations. Java uses naming scheme where package and public
class names must follow directory and file names respectively. This naming scheme
allows Java compiler to locate library files.
Widening Primitive Conversion in Java
Here is a small code snippet given. Try to Guess the output
public class Test
System.out.print("Y" + "O");
System.out.print('L' + 'O');
Arrays in Java
An array is a group of like-typed variables that are referred to by a common
name.Arrays in Java work differently than they do in C/C++. Following are some
important point about Java arrays.
In Java all arrays are dynamically allocated.(discussed below)
Since arrays are objects in Java, we can find their length using member length. This is
different from C/C++ where we find length using sizeof.
A Java array variable can also be declared like other variables with [] after the data type.
The variables in the array are ordered and each have an index beginning from 0.
Java array can be also be used as a static field, a local variable or a method parameter.
The size of an array must be specified by an int value and not long or short.
The direct superclass of an array type is Object.
Every array type implements the interfaces Cloneable and java.io.Serializable.
import java.util.Arrays;
{ return false;
else {
int mid=(left+right)/2;
if (arr[mid]==key)
return true;
else if(arr[mid]>key)
right=mid-1;
return binaryS(arr,left,right,key);
else {
left=mid+1;
return binaryS(arr,left,right,key);
}
}
int n=sc.nextInt();
arr[i]=sc.nextInt();
Arrays.sort(arr);
int key=sc.nextInt();
boolean s=binaryS(arr,0,n-1,key);
System.out.println(s);
import java.io.*;
class Differ
{
public static void main(String args[])
throws IOException
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter an integer");
int a = Integer.parseInt(br.readLine());
System.out.println("Enter a String");
String b = br.readLine();
System.out.printf("You have entered:- " + a +
" and name as " + b);
}
}
java.util.Scanner class is a simple text scanner which can parse primitive types and
strings. It internally uses regular expressions to read different types.
Java.io.BufferedReader class reads text from a character-input stream, buffering
characters so as to provide for the efficient reading of sequence of characters
BufferedReader – (fast, but not recommended as it requires lot of typing): The
Java.io.BufferedReader class reads text from a character-input stream, buffering characters so
as to provide for the efficient reading of characters, arrays, and lines. With this method we will
have to parse the value every time for desired type. Reading multiple words from single line
adds to its complexity because of the use of Stringtokenizer and hence this is not
recommended. This gets accepted with a running time of approx 0.89 s.but still as you can see
it requires a lot of typing all together and therefore method 3 is recommended.
filter_none
edit
play_arrow
brightness_4
// Working program using BufferedReader
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int k = Integer.parseInt(st.nextToken());
int count = 0;
int x = Integer.parseInt(br.readLine());
if (x%k == 0)
count++;
System.out.println(count);
In Scanner class if we call nextLine() method after any one of the seven nextXXX()
method then the nextLine() doesn’t not read values from console and cursor will not
come into console it will skip that step. The nextXXX() methods are nextInt(),
nextFloat(), nextByte(), nextShort(), nextDouble(), nextLong(), next().
In BufferReader class there is no such type of problem. This problem occurs only for
Scanner class, due to nextXXX() methods ignore newline character and nextLine() only
reads till first newline character. If we use one more call of nextLine() method between
nextXXX() and nextLine(), then this problem will not occur because nextLine() will
consume the newline character. See this for the corrected program. This problem is
same as scanf() followed by gets() in C/C++.
Fibonaaci dynamic
import java.util.*;
import java.io.*;
import java.util.Arrays;
public class helloworld {
public static int[] fib(int n)
{
int ar[]=new int[n+1];
ar[0]=0;
ar[1]=1;
for (int i=2;i<=n;i++)
{
ar[i]=ar[i-2]+ar[i-1];
}
return ar;
int arr[]=fib(n);
for(int var:arr)
{
System.out.println(var);
}
}
catch(IOException e){
e.printStackTrace();
}