Get Started With Java Easy Guide - COFPROG

Get Started With Java Easy Guide

CORE JAVA BASICS

WHY Java ?

1. Simple & robust.
2. Platform or architecture independent
3. Secure
4. Automatic memory management.

------------
Get Started With Java Easy Guide
Get Started With Java Easy Guide

Prerequisites :


1. JDK 1.8(Java SE 8)  must be installed using java installer.
2. 1st entry of path must be
<JDK1.8>\bin
3. How to set path ?
My Computer --- R Click -- Properties --- Advanced --- Environment variables --- System Variables --- Edit Path --- Add 1st entry as <jdk1.8>\bin
DO NOT delete existing path.
Confirm it.
How ?
Open cmd prompt
Type set path
It should show you --path info --- where 1st entry is <jdk1.8>\bin .

Type from cmd prompt
java -version


4. Create empty workspace. Create folders day wise. Create src & bin to store java sources & .class files separately.

Rules on Identifiers

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

Norms
class , interfaces , enum names-  must start with upper case & then follow camel case
data members/methods(funs) --  must start with lower case & then follow camel case
constants -- all uppercase.


Objective --- create a java appln to display welcome msg on the console.


Legal class level access specifiers - default(scope=current pkg only), public (scope=accessible form any where)

compiler usage --- javac -d ..\bin First.java--> place the .class files to bin folder

Objective : accept 2 nums as cmd line args , add them & disp the result.




API -- java docs
java.lang  => pkg name  --default
Integer -- class
public static int parseInt(String s) throws NumberFormatException


Basic rules
0. Files with no public classes can have a name that does not match any of the classes in the file
1. There can be only one public class per source code file.
2. 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.
3.  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.
4. 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.
5. 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.
6. A file can have more than one non public class.


Automatic conversions(widening ) ---Automatic promotions
byte--->short--->int---> long--->float--->double
char ---> int
Rules ---
src & dest - must be compatible, typically dest data type must have higher precision that src data type.
Any arithmetic operation involving bytes --- result type=int
Any arithmetic op involving short --- result type=int
int & long ---> long
long & float ---> float
byte,short......& float & double----> double

Narrowing conversion --- forced conversion(type-casting)
eg ---
double ---> int
double ---> float


Steps for attaching scanner -- data read from console
1. import java.util.*; or import java.util.Scanner;
2. create instance of Scanner class
constr -- Scanner (InputStream in)
System.in --- stdin
usage -- Scanner sc=new Scanner(System.in);
3.To check data type
boolean hasNextInt(),hasNextByte(),hasNextLong()......
4. To read data
int nextInt() throws InputMismatchException
double nextDouble() throws InputMismatchException


Class Programming

Encapsulation -- consists of Data hiding + Data Abstraction
Data hiding -- achieved by private data members.
Data Abstraction -- achieved by supplying an interface to the Client (customer) .Highlighting only WHAT is to be done & not highlighting HOW it's internally implemented.


Adv ---security
ease of maintenance
ease of usage
ensures easy modification




Objective --- Create Java appln for follow. -represent 3D Box----
D.M -width,height,depth : double --- private
constr-  to init Box params.
Business logic(behaviour) --- displayBoxDims(void ret) ,calcVolume(ret vol)


Create Java application -- which allows user to supply 3 dims as cmd line args. --- create Box object & display dims & display vol.

Create Java application -- which allows user to supply 3 dims from user using scanner. --- create Box object & display dims & display vol.



Pointers vs java references

pointer arithmatic is not allowed in java.
reference --- holds internal representation of address --



pointer arithmatic is not allowed in java.
reference --- holds internal representation of address --


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

Javac doesn't allow accessing ANY (prim type or ref type) un-initialized data member.

Automatic Gargabe Collection --- to avoid mem. leaks/holes

JRE creates 2 thrds --- main thrd(to exec main() sequentially) -- fg thrd
G.C --- daemon thrd ---bg thrd --- gets activated periodically  --- releases the memory occupied by un-referenced objects allocated on the heap(the obj whose no. of ref=0)
To release/close non- Java resources.(eg - closing of Db conn, closing file handles  is NOT done auto. by GC)
Garbage= un -reachable object.

Array handling

Objective -- Accept no of data samples(double)
Create array & display -- def vals
Accept data from User(scanner) & store it in suitable array.
Display array data from for loop.


Objective --- Accept from user --- no of boxes to be made.
Accept box dims from user & display box dims using for-each

--------------------------

Regarding Packages:


What is a package ?
Collection of functionally similar classes & interfaces.

Creating user defined packages
Need ?
1. To group functionally similar classes together.
2. Avoids name space collision
3. Finer control over access specifiers.

About Packages
1. Creation : package stmt has to be placed as the 1st stmt in Java source.
eg : package p1; => the classes will be part of package p1.
2.Package names are mapped to folder names.
eg : package p1; class A{....}
A.class must exist in folder p1.
3.  For simplicity --- create folder p1 -- under <src> & compile from <src>
From <src>
javac -d ..\bin p1\A.java

-> javac will auto. create the sub-folder <p1> under the <bin> folder & place A.class within <p1>



NOTE : Its not mandatory to create java sources(.java) under package named folder. BUT its mandatory to store packged compiled classes(.class) under package named folders

Earlier half is just maintained as convenience(eg --- javac can then detect auto. dependencies & compile classes ).


4. To run the pkged classes from any folder : u must set Java specific  env var. : classpath
set classpath=g:\dac1\day2\bin;

With the classpath set, JVM's classloader 1st searches in the curnt folder, if not found then will continue to search in the folders specified in the classpath & try to load the pkged classes.

classpath= Java only env .var
Used by JRE's classloader : to locate & load the classes.
Classloader will try to locate the classes from current folder, if not found --- will refer to classpath entries : to resolve & load Java classes.

What should be value of classpath ---Must be set to top of pakged hierarchy(i.e .class eg : bin)
set classpath=G:\dac\dac1\day2\bin;(cmd line invocation)
-----------------------------------------------

Long to Float Conversions in Java: 


The range of values that can be represented by a float or double is much larger than the range that can be represented by a long. Although one might lose significant digits when converting from a long to a float, it is still a "widening" operation because the range is wider.

From the Java Language Specification, §5.1.2:

A widening 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, using IEEE 754 round-to-nearest mode (§4.2.4).
Note that a double can exactly represent every possible int value.

What are the rules for naming variables in java?

Answer:
All variable names must begin with a letter of the alphabet, an underscore ( _ ), or a dollar sign ($). Can't begin with a digit.  The rest of the characters may be any of those previously mentioned plus the digits 0-9.

The convention is to always use a (lower case) letter of the alphabet. The dollar sign and the underscore are discouraged. 
Previous
Next Post »