Java Tutorial

JDK Vs JRE Vs JVM

https://techglot.tech.blog/2019/10/07/interview-questions/3/

JVM

https://techglot.tech.blog/category/core-java/java-tutorial/jvm-runtime-vm/

Rules for identifiers(i.e name of type)

  1. Identifiers must start with a letter, a currency character ($), or a connecting character such as the underscore ( _ ), cannot start with a number!
  2. Can’t use a Java keyword as an identifier.
  3. Are Case sensitive

Norms

  1. Class , Interfaces , Enum names- must start with upper case & then follow camel case
  2. Data members/methods(funs) — must start with lower case & then follow camel case
  3. constants — all uppercase.

Legal class level Access-specifiers – (only two of four)

  1. default(scope=current pkg only),
  2. public (scope=accessible form any where)

Basic rules related to class and java files

  1. Files with no public classes can have a name that does not match any of the classes in the file
  2. There can be only one public class per source code file.
  3. If there is a public class in a file, the name of the file must match the name of the public class. For example, a class declared as public class Example { } must be in a source code file named Example.java.
  4. If the class is part of a package, the package statement must be the first line in the source code file, before any import statements that may be present.
  5. If there are import statements, they must go between the package statement (if there is one) and the class declaration. If there isn’t a package statement, then the import statement(s) must be the first line(s) in the source code file. If there are no package or import statements, the class declaration must be the first line in the source code file.
  6. import and package statements apply to all classes within a source code file. In other words, there’s no way to declare multiple classes in a file and have them in different packages, or use different imports.
  7. A file can have more than one non public class.

Automatic Conversion

As per Java language specs ——
Widening primitive conversions do not lose information about the overall magnitude of a numeric value. Indeed, conversions widening from an integral type to another integral type do not lose any information at all; the numeric value is preserved exactly. Conversions widening from float(4byte) to double(8byte) in strictfp expressions also preserve the numeric value exactly; however, such conversions that are not strictfp may lose information about the overall magnitude of the converted value.

Conversion of an int(4byte) or a long(8byte) value to float(4byte), or of a long value to double, may result in loss of precision-that is, the result may lose some of the least significant bits of the value. In this case, the resulting floating-point value will be a correctly rounded version of the integer value, using IEEE 754 round-to-nearest mode 

In other words even though you may lose information, you know that the value will still be in the overall range of the target type.

Widening Primitive Conversion

The following 19 specific conversions on primitive types are called the widening primitive conversions:

    byte to short, int, long, float, or double
    short to int, long, float, or double
    char to int, long, float, or double
    int to long, float, or double
    long to float or double
    float to double

Widening primitive conversions do not lose information about the overall magnitude of a numeric value.

Conversion of an int or a long value to float, or of a long value to double, may result in loss of precision-that is, the result may lose some of the least significant bits of the value. In this case, the resulting floating-point value will be a correctly rounded version of the integer value

Read it twice if needed!
To put it another way, the JLS(Java language specification) distinguishes between a loss of magnitude and a loss of precision.

int to byte for example is a (potential) loss of magnitude because you can’t store 500 in a byte.

long to float is a potential loss of precision but not magnitude because the value range for floats is larger than that for longs.

So the rule is:

Loss of magnitude: explicit cast required;
Loss of precision: no cast required.

Regarding primitive types

Automatic conversions(widening ) —Automatic promotions

byte—>short—>int—> long—>float—>double

char —> int

Rules related to promotion of primitives

  1. src & dest – must be compatible, typically dest data type must have higher precision that src data type.
  2. Any arithmetic operation[TODO code snippet]
    1. involving bytes — result type=int
    1. Any arithmetic op involving short — result type=int
    2. int & long —> long
    3. long & float —> float
    4. byte,short……& float & double—-> double

Narrowing conversion — forced conversion(type-casting)

  1. double —> int
  2. double —> float

Datatype ranges

Data TypeSize (bits)Minimum ValueMaximum Value
byte8-128127
short16-32,76832,767
int32-2,147,483,6482,147,483,647
long64-9,223,372,036,854,775,8089,223,372,036,854,775,807
float321.40129846432481707e-453.40282346638528860e+38
double644.94065645841246544e-3241.79769313486231570e+308
booleanTypically 1true or falsetrue or false
char16065,535

Object oriented principles

Refer interview section(TODO- link here)

  1. Encapsulation –– consists of Data hiding + Data Abstraction
    1. Information hiding — achieved by private data members & supplying public accessors.
  2. Abstraction — achieved by supplying an interface to the Client (customer) .Highlighting only WHAT is to be done & not highlighting HOW it’s internally implemented.

Advantages of OOPS Principal

  1. security
  2. ease of maintenance
  3. ease of usage
  4. ensures easy modification

method local vars Vs instance data members

  1. method local vars — allocated on stack, def. — uninitialized.
  2. inst. data members — allocated on heap, inited to def vals(eg – boolean -false,int -0,double 0.0, ref-null)

Static keyword in java

Usages

  1. static data members –— Mem allocated only once @ class loading time — not saved on object heap — but in special mem area — meta space . — shared across all objects of the same class.
    • Initialized to their default values(eg — boolean -false,ref -null)
    • How to refer ? — className.memberName
  2. static methods –— Can be accessed w/o instantiation. (ClassName.memberName(….))
    • Can’t access ‘this’ or ‘super’ from within static method.

Rules

  • Can static methods access other static members directly(w/o inst) — YES
  • Can static methods access other non-static members directly(w/o inst) — NO
  • Can non-static methods access other static members directly(w/o inst) — YES
  1. static import —Can directly use all static members from the specified class.
import static java.lang.System.*;
main(...)
{
   out.println(.....);
}
  1. static initializer blocks
    • They appear — within class definition & can access only static members directly.(w/o inst)
syntax --
static {
// block gets called only once @ class loading time
// usage -- to init all static data members 
//& can add functionality -which HAS to be called precisely once.
}
  • Regarding non-static initilizer blocks(inst initilaizer block)
syntax
{
//will be called per instantiation --- before matching constructor
//Better alternative --- parameterized constructor.
}

Order of call- static block (once during class loading)–> instance-block(before Constructor & after super) –>Constructor

//Super class
public class A {
A(){
	System.out.println("4.A constructor");
};
{
	System.out.println("3.A instance block");
	}
static {
	System.out.println("1.A static");
}
}
//child class
public class B extends A {

	public B() {
		super();
		System.out.println("6.B construcotr");
	}

	public static void main(String[] args) {
		 B a=new B();//if no instance then only static block executed in order

	}

	{
		System.out.println("5.B instance block");
	}
	static {
		System.out.println("2.B static");
	}

}
  1. static nested classes
class Outer {
// static & non-static members
  static class Nested
  {
     //can access ONLY static members of the outer class DIRECTLY(w/o inst)
  }
}

Keyword this and super

  1. Only a constr can use this() or super()
  2. Has to be 1st statement in the constr
  3. Any constructor can never have both ie. this() & super()
  4. super & this (w/o brackets) are used to access (visible) members of super class or the same class.

foreach syntax(enhanced for loop

int[] ints={1,2,3,4,5};//dyn init of array
for(int data : ints) //data=ints[0],.....data[ints.length-1]
  sop(data);

Limitations

  1. for-each works on a copy –can’t used to modify array elems.
  2. for-each — from 1st elem –last elem , step size = +1

Access Modifiers

Published by

Unknown's avatar

sevanand yadav

software engineer working as web developer having specialization in spring MVC with mysql,hibernate

One thought on “Java Tutorial”

Leave a comment