Sei sulla pagina 1di 23

 Java is a simple language: Java is easy to learn and its syntax is clear and

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.

JVM Shutdown Hook in Java


Shutdown Hooks are a special construct that allow developers to plug in a piece of code
to be executed when the JVM is shutting down. This comes in handy in cases where we
need to do special clean up operations in case the VM is shutting down.

Differences between JDK, JRE and JVM


JAVA DEVELOPMENT KIT
The Java Development Kit (JDK) is a software development environment used for
developing Java applications and applets. It includes the Java Runtime Environment
(JRE), an interpreter/loader (Java), a compiler (javac), an archiver (jar), a
documentation generator (Javadoc) and other tools needed in Java development.
JAVA RUNTIME ENVIRONMENT
JRE stands for “Java Runtime Environment” and may also be written as “Java
RTE.” The Java Runtime Environment provides the minimum requirements for
executing a Java application; it consists of the Java Virtual Machine (JVM), core
classes, and supporting files.
JAVA VIRTUAL MACHINE

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.

Does JVM create object of Main class (the class with


main())?
Consider following program.

class Main {

public static void main(String args[])

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.

Is main method compulsory in Java?


The answer to this question depends on version of java you are using. Prior to JDK 5,
main method was not mandatory in a java program.
 You could write your full code under static block and it ran normally.
 The static block is first executed as soon as the class is loaded before the
main(); method is invoked and therefore before the main() is called. main is usually
declared as static method and hence Java doesn’t need an object to call main
method.
However, From JDK6 main method is mandatory.

Myth about the file name and class name in Java


/***** File name: Trial.java ******/
class Geeks
{
public static void main(String[] args) {
System.out.println("Hello world");
}
}
Step 1: javac Trial.java
Step1 will create a Geeks.class (byte code) without any error message since the class
is not public.
Step 2: java Geeks
So it will not throw error if compiled by file name and executed by the name of the main class

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.

public class String


{
public static void main (String[] args)
{
System.out.println("I got confused");
}
}

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;
}
}

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.

Java has two categories of data:


 Primitive data (e.g., number, character)
 Object data (programmer created types)

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).

Declaration of enum in java :


 Enum declaration can be done outside a Class or inside a Class but not inside a
Method.
// A simple enum example where enum is declared
// outside any class (Note enum keyword instead of
// class keyword)
enum Color
{
RED, GREEN, BLUE;
}

public class Test


{
// Driver method
public static void main(String[] args)
{
Color c1 = Color.RED;
System.out.println(c1);
}
}
Output :
RED

// enum declaration inside a class.


public class Test
{
enum Color
{
RED, GREEN, BLUE;
}

// 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

SUNDAY, MONDAY, TUESDAY, WEDNESDAY,

THURSDAY, FRIDAY, SATURDAY;

// Driver class that contains an object of "day" and

// main().

public class Test

Day day;

// Constructor

public Test(Day day)

this.day = day;

// Prints a line about Day using switch

public void dayIsLike()

switch (day)

case MONDAY:

System.out.println("Mondays are bad.");


break;

case FRIDAY:

System.out.println("Fridays are better.");

break;

case SATURDAY:

case SUNDAY:

System.out.println("Weekends are best.");

break;

default:

System.out.println("Midweek days are so-so.");

break;

// Driver method

public static void main(String[] args)

String str = "MONDAY";

System.out.println(Day.valueOf(str));

Test t1 = new Test(Day.valueOf(str));

t1.dayIsLike();

values(), ordinal() and valueOf() methods :


 These methods are present inside java.lang.Enum.
 values() method can be used to return all values present inside enum.
 Order is important in enums.By using ordinal() method, each enum constant
index can be found, just like array index.
 valueOf() method returns the enum constant of the specified string value, if
exists.
StringBuffer appendCodePoint() Method in Java with
Examples
The java.lang.StringBuffer.appendCodePoint(int cp)is the method which appends the
string representation of the codePoint argument to this sequence.
Syntax :
public StringBuffer appendCodePoint(int cp)
Parameters : The method accepts a single parameter cp of integer type and refers to
the Unicode code point.

// Java praogram to illustrate the

// java.lang.StringBuffer.appendCodePoint(int cp)

import java.lang.*;

public class Geeks {

public static void main(String[] args)

StringBuffer sbf = new StringBuffer("Geeksforgeeks");

System.out.println("String buffer = " + sbf);

// Here it appends the CodePoint as

// String to the string buffer

sbf.appendCodePoint(65);

System.out.println("After appending CodePoint is = " + sbf);

}
}

Scope of Variables In Java


These variables must be declared inside class (outside any function). They can be directly
accessed anywhere in class

Member variables can be accessed outside a class with following rules


Modifier Package Subclass World

public Yes Yes Yes

protected Yes Yes No

Default (no
modifier) Yes No No

private No No No

As an exercise, predict the output of following Java program.

public class Test


{
static int x = 11;
private int y = 33;
public void method1(int x)
{
Test t = new Test();
this.x = 22;
y = 44;

System.out.println("Test.x: " + Test.x);


System.out.println("t.x: " + t.x);
System.out.println("t.y: " + t.y);
System.out.println("y: " + y);
}

public static void main(String args[])


{
Test t = new Test();
t.method1(5);
}
}
Output:
Test.x: 22
t.x: 22
t.y: 33
y: 44
Loop Variables (Block Scope)
A variable declared inside pair of brackets “{” and “}” in a method has scope withing the
brackets only.
filter_none
edit
play_arrow
brightness_4
public class Test
{
public static void main(String args[])
{
{
// The variable x has scope within
// brackets
int x = 10;
System.out.println(x);
}

// Uncommenting below line would produce


// error since variable x is out of scope.

// System.out.println(x);
}
}

Blank Final in Java


A final variable in Java can be assigned a value only once, we can assign a value either
in declaration or later.
Java bounded type parameters

Enhanced For loop


Java also includes another version of for loop introduced in Java 5. Enhanced for loop
provides a simpler way to iterate through the elements of a collection or array. It is
inflexible and should be used only when there is a need to iterate through the elements
in sequential manner without knowing the index of currently processed element.
Also note that the object/variable is immutable when enhanced for loop is used i.e it
ensures that the values in the array can not be modified, so it can be said as read only
loop where you can’t update the values as opposite to other loops where values can be
modified.
We recommend using this form of the for statement instead of the general form
whenever possible.(as per JAVA doc.)
Syntax:
for (T element:Collection obj/array)
{
statement(s)
}
Lets take an example to demonstrate how enhanced for loop can be used to simpify the
work. Suppose there is an array of names and we want to print all the names in that
array. Let’s see the difference with these two examples
Enhanced for loop simplifies the work as follows-

// Java program to illustrate enhanced for loop


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]);
}
*/
}
}
Output:
Ron
Harry
Hermoine
Enhanced for-loop:
1. String[] array = ["hello", "world"];
2.
3. for (String item : array) {
4. System.out.println("Item: " + item);
5. }
forEach() method:
1. String[] array = ["hello", "world"];
2.
3. array.forEach(item -> System.out.println("Item: " + item));
Limitations of for-each loop
1. For-each loops are not appropriate when you want to modify the array:
2. for (int num : marks)
3. {
4. // only changes num, not the array element
5. num = num*2;
6. }
7. For-each loops do not keep track of index. So we can not obtain array index
using For-Each loop
8. for (int num : numbers)
9. {
10. if (num == target)
11. {
12. return ???; // do not know the index of num
13. }
14. }
15. For-each only iterates forward over the array in single steps
16. // cannot be converted to a for-each loop
17. for (int i=numbers.length-1; i>0; i--)
18. {
19. System.out.println(numbers[i]);
20. }
21. For-each cannot process two decision making statements at once
22. // cannot be easily converted to a for-each loop
23. for (int i=0; i<numbers.length; i++)
24. {
25. if (numbers[i] == arr[i])
26. { ...
27. }
}
Better than if-else: The Java compiler generates generally more efficient bytecode from switch
statements that use String objects than from chained if-then-else statements

Do we need forward declarations in Java?


Predict output of the following Java program.

// filename: Test2.java

// main() function of this class uses Test1 which is declared later in

// this file

class Test2 {

public static void main(String[] args) {

Test1 t1 = new Test1();

t1.fun(5);

class Test1 {

void fun(int x) {

System.out.println("fun() called: x = " + 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

public static void main(String[] args)

System.out.print("Y" + "O");

System.out.print('L' + 'O');

At first glance, we expect “YOLO” to be printed.


Actual Output:
“YO155”.
Explanation:
When we use double quotes, the text is treated as a string and “YO” is printed, but
when we use single quotes, the characters ‘L’ and ‘O’ are converted to int. This is called
widening primitive conversion. After conversion to integer, the numbers are added ( ‘L’ is
76 and ‘O’ is 79) and 155 is printed.

Does Java support goto?


Java does not support goto, it is reserved as a keyword just in case they wanted to add
it to a later version.
 Unlike C/C++, Java does not have goto statement, but java supports label.
 The only place where a label is useful in Java is right before nested loop
statements.
 We can specify label name with break to break out a specific outer loop.
 Similarly, label name can be specified with continue.
Using break with label in Java

// Java code to illustrate


// using label and break
// instead of goto

// file name: Main.java


public class Main {
public static void main(String[] args)
{

// label for outer loop


outer:
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if (j == 1)
break outer;
System.out.println(" value of j = " + j);
}
} // end of outer loop
} // end of main()
} // end of class Main
Output:
value of j = 0

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.

Scanner Class in Java


Scanner is a class in java.util package used for obtaining the input of the primitive types
like int, double, etc. and strings. It is the easiest way to read input in a Java program,
though not very efficient if you want an input method for scenarios where time is a
constraint like in competitive programming.
 To create an object of Scanner class, we usually pass the predefined object
System.in, which represents the standard input stream. We may pass an object of
class File if we want to read input from a file.
 To read numerical values of a certain data type XYZ, the function to use is
nextXYZ(). For example, to read a value of type short, we can use nextShort()
 To read strings, we use nextLine().
 To read a single character, we use next().charAt(0). next() function returns the
next token/word in the input as a string and charAt(0) function returns the first
character in that string.
Binary Search in java
import java.util.*;

import java.util.Arrays;

public class helloworld {

public static boolean binaryS(int[] arr,int left,int right,int key)

if(left > right)

{ 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);

}
}

public static void main(String[] args) {

// TODO Auto-generated method stub

Scanner sc=new Scanner(System.in);

System.out.println("Enter size of array");

int n=sc.nextInt();

int arr[]=new int[n];

System.out.println("Enter array elements");

for(int i=0;i< n;i++)

arr[i]=sc.nextInt();

Arrays.sort(arr);

System.out.println("Enter key value");

int key=sc.nextInt();

boolean s=binaryS(arr,0,n-1,key);

System.out.println(s);

Java Scanner hasNext() Method


The hasNext() is a method of Java Scanner class which returns true if this scanner has
another token in its input. There are threedifferent types of Java
Scanner hasNext() method which can be differentiated depending on its parameter. These
are:

1. Java Scanner hasNext () Method

2. Java Scanner hasNext (String pattern) Method

3. Java Scanner hasNext(Pattern pattern) Method

1.Java Scanner hasNext () Method:


It is a Scanner class method which returns true if this scanner has another token in its
input. This method may block while waiting for input to scan.

2.Java Scanner hasNext (String pattern)


Method:
It is a Scanner class method which returns true if the next token matches the pattern
constructed from the specified string.

3.Java Scanner hasNext (Pattern pattern)


Method:
It is a Scanner class method which returns true if the next complete token matches the
specified pattern.

Difference between Scanner and BufferReader


Class in Java

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;

public class Main

public static void main(String[] args) throws IOException

BufferedReader br = new BufferedReader(

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;

while (n-- > 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;

public static void main(String[] args) {


// TODO Auto-generated method stub
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n;
try
{
n=Integer.parseInt(br.readLine());

int arr[]=fib(n);

for(int var:arr)
{
System.out.println(var);
}
}
catch(IOException e){
e.printStackTrace();
}

Potrebbero piacerti anche