CORE JAVA
What is a language
So many concepts(oops + other)
Craming these concepts
Frameworks
Java history
How java works
Java basic programs and SO CALLED FUNDA’S
How concepts are implemented in java
Major application markets
how logics are implemented in such apps
What is language
Interpreter
Based on need
What does it comprise of
Keywords
Tokens
Scope
Universal concepts
Variables
Methods
Loops
Compilation
Error
Exceptions
Complexity
Usage/requirement
So many concepts
oops
Object
Inheritance
Encapsulation
Polymorphism
Message passing
Access modifiers (hierarchy and package)--
Abstraction
Others
Serialization
Threading and Multithreading
Interface vs. Abstract
Exception handling (try and catch)
Framework usage
Database Oriented
UI Oriented
Controller Based
Security Based
Project building (jar or exe)
Craming these concepts
Real world and application examples
Building logics
Implementation
Using frameworks
Readable programs
Optimizing code
Frameworks
(View, Controller, Model, Services, Business Layer, DAL, Presentation Layer, Unit Tests)
MVC
MVP
MVVM
ZEND
Different types (depends on product requirement)
Mvc (most used)
Mvc explained completely with example
JAVA
Java history
Developed by James Gosling at Sun Microsystems (which is now a subsidiary of Oracle Corporation (1995?)
The language was initially called Oak after an oak tree that stood outside Gosling's office; it went by the
name Green later, and was later renamed Java, from Java coffee, said to be consumed in large quantities by the language's
creators.
JDK 1.0 (January 23, 1996)
JDK 1.1 (February 19, 1997)
J2SE 1.2 (December 8, 1998)
J2SE 1.3 (May 8, 2000)
J2SE 1.4 (February 6, 2002)
J2SE 5.0 (September 30, 2004)
Java SE 6 (December 11, 2006)
Java SE 7 (July 28, 2011)
How java works
JVM
Bytecode
Package
.java
.class
Setting path
Libraries
Jre
Java basic programs and SO CALLED FUNDA’S
Not pure object oriented language(primitive variables)
Automatic garbage collection
Multithreading
Access modifiers
Class-public and default
Member(Function or variable)-public,private,protected,default
Synchronization
SIMPLE HELLO WORLD PROGRAM
class HelloWorld
{
public static void main(String args[])
{
System.out.println("Hello World!");
}
}
Data types
Primitive Data Type Default Value (for fields)
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char '\u0000'
String (or any object) null
boolean false
Non Primitive Data Type
Arrays
Enum
Class
Structure
Keywords
abstract continue float new switch
***
assert default for package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
****
case enum instanceof return transient
catch extends int short try
char final interface static void
**
class finally long strictfp volatile
*
const finalize native super while
* not used
**
added in 1.2
***
added in 1.4
****
added in 5.0
Control statements
If
if (booleanExpression1) {
// statements
} else if (booleanExpression2) {
// statements
}
...
else {
// statements}
while
while (Boolean expression) {
Statements…
}
for
for ( init ; booleanExpression ; update ) {
statement (s)
}
switch
switch (expression) {
case value_1 :
statement (s);
break;
case value_2 :
statement (s);
break;
.
case value_n :
statement (s);
break;
default:
statement (s);
}
return
EXAMPLES
public class IFMainClass {
public static void main(String[] args) {
int a = 2;
if (a == 1) {
System.out.println("one");
} else if (a == 2) {
System.out.println("two");
} else if (a == 3) {
System.out.println("three");
} else {
System.out.println("invalid");
}
}
}
public class SWITCHMainClass {
public static void main(String[] args) {
int i = 1;
switch (i) {
case 1 :
System.out.println("One.");
break;
case 2 :
System.out.println("Two.");
break;
case 3 :
System.out.println("Three.");
break;
default:
System.out.println("You did not enter a valid value.");
}
}
}
public class FORMainClass {
public static void main(String[] args) {
for (int i = 0; i myList = new ArrayList();
myList.add("A");
myList.add("B");
myList.add("C");
myList.add("D");
Set mySet = new HashSet(myList);
for (Object theFruit : mySet)
System.out.println(theFruit);
}
}
/*
D
A
B
C
*/
Stack Basics: last-in, first-out behavior
The java.util.Stack class is a Collection that behaves in a last-in-first-out (LIFO) manner.
import java.util.Stack;
public class MainClass {
public static void main (String args[]) {
Stack s = new Stack();
s.push("A");
s.push("B");
s.push("C");
s.pop();
System.out.println(s);
}
}
[A, B]
Convert a Queue to a List
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class Main {
public static void main(String[] args) {
Queue myQueue = new LinkedList();
myQueue.add("A");
myQueue.add("B");
myQueue.add("C");
myQueue.add("D");
List myList = new ArrayList(myQueue);
for (Object theFruit : myList)
System.out.println(theFruit);
}
}
/*
A
B
C
D
*/
Generics
Life without Generics
When retrieving a member from stringList1, you get an instance of java.lang.Object. In order to work with the original
of the member element, you must first downcast it to String.
import java.util.ArrayList;
import java.util.List;
public class MainClass {
public static void main(String[] args) {
List stringList1 = new ArrayList ();
stringList1.add ("Java 5");
stringList1.add ("with generics");
String s1 = (String) stringList1.get(0);
}}
The term generics means parameterized types
1. T is a type parameter that will be replaced by a real type.
2. T is the name of a type parameter.
3. This name is used as a placeholder for the actual type that will be passed to Gen when an object is created.
class GenericClass {
T ob;
GenericClass(T o) {
ob = o;
}
T getob() {
return ob;
}
void showType() {
System.out.println("Type of T is " + ob.getClass().getName());
}
}
public class MainClass {
public static void main(String args[]) {
// Create a Gen reference for Integers.
GenericClass iOb = new GenericClass(88);
iOb.showType();
// no cast is needed.
int v = iOb.getob();
System.out.println("value: " + v);
// Create a Gen object for Strings.
GenericClass strOb = new GenericClass("Generics Test");
strOb.showType();
String str = strOb.getob();
System.out.println("value: " + str);
}
}
Type of T is java.lang.Integer
value: 88
Type of T is java.lang.String
value: Generics Test
Generics Work Only with Objects
Gen strOb = new Gen(53); // Error, can't use primitive type
Working with generic List
import java.util.ArrayList;
import java.util.List;
public class MainClass {
public static void main(String[] args) {
List stringList1 = new ArrayList();
stringList1.add("Java 5");
stringList1.add("with generics");
String s1 = (String) stringList1.get(0);
System.out.println(s1.toUpperCase());
List stringList2 = new ArrayList();
stringList2.add("Java 5");
stringList2.add("with generics");
String s2 = stringList2.get(0);
System.out.println(s2.toUpperCase());
}
}
JAVA 5
JAVA 5
Type
Using Generic Comparable interface
import java.util.Arrays;
class Person implements Comparable {
public Person(String firstName, String surname) {
this.firstName = firstName;
this.surname = surname;
}
public String toString() {
return firstName + " " + surname;
}
public int compareTo(Person person) {
int result = surname.compareTo(person.surname);
return result == 0 ? firstName.compareTo(((Person) person).firstName) : result;
}
private String firstName;
private String surname;
}
public class MainClass {
public static void main(String[] args) {
Person[] authors = {
new Person("D", "S"),
new Person("J", "G"),
new Person("T", "C"),
new Person("C", "S"),
new Person("P", "C"),
new Person("B", "B") };
Arrays.sort(authors); // Sort using Comparable method
System.out.println("\nOrder after sorting into ascending sequence:");
for (Person author : authors)
{ System.out.println(author); }
Person[] people = {
new Person("C", "S"),
new Person("N", "K"),
new Person("T", "C"),
new Person("C", "D") };
int index = 0;
System.out.println("\nIn search of authors:");
for (Person person : people) {
index = Arrays.binarySearch(authors, person);
if (index >= 0) {
System.out.println(person + " was found at index position " + index);
} else {
System.out.println(person + "was not found. Return value is " + index);
}}}}
Order after sorting into ascending sequence:
B B
P C
T C
J G
C S
D S
In search of authors:
C S was found at index position 4
N Kwas not found. Return value is -5
T C was found at index position 2
C Dwas not found. Return value is -4
Creating a Generic Method
public class MainClass {
static boolean isIn(T x, V[] y) {
for (int i = 0; i {
public LinkedList() {
}
public LinkedList(T item) {
if (item != null) {
current = end = start = new ListItem(item);
}
}
public LinkedList(T[] items) {
if (items != null) {
for (int i = 0; i polyline = new LinkedList();
polyline.addItem(new Point(1, 2));
polyline.addItem(new Point(2, 3));
Point p = polyline.getFirst();
System.out.println(p);
}
}
java.awt.Point[x=1,y=2]
i/o
Readline
import java.io.*;
class ReadLine
{
public static void main(String[] args) throws IOException
{
String CurLine = "";
System.out.println("Enter a line of text (type 'quit' to exit): ");
InputStreamReader converter = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(converter);
while (!(CurLine.equals("quit")))
{
CurLine = in.readLine();
if (!(CurLine.equals("quit")))
{
System.out.println("You typed: " + CurLine);
}
}
}
}
InputStreamReader
1. An InputStreamReader reads bytes and translates them into characters using the specified character set.
2. InputStreamReader is ideal for reading from the output of an OutputStreamWriter or a PrintWriter.
The InputStreamReader class has four constructors:
public InputStreamReader (InputStream in)
public InputStreamReader (InputStream in, java.nio.charset.Charset cs)
public InputStreamReader (InputStream in, java.nio.charset.CharsetDecoder, dec)
public InputStreamReader (InputStream in, String charsetName)
To create an InputStreamReader:
InputStreamReader reader = new InputStreamReader(new FileInputStream (filePath), charSet);
Get a class of an object
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
Person p = new Person("A");
Animal a = new Animal("B");
Thing t = new Thing("C");
String text = "hello";
Integer number = 1000;
List list = new ArrayList();
list.add(p);
list.add(a);
list.add(t);
list.add(text);
list.add(number);
for (int i = 0; i -1) {
return str1.substring(str2.length());
}
return str1;
}
}
Obtaining the Characters in a String as an Array of Bytes
public class MainClass {
public static void main(String[] arg) {
String text = "To be or not to be"; // Define a string
byte[] textArray = text.getBytes();
for(byte b: textArray){
System.out.println(b);
}
}
}
84
111
32
98
101
32
111
114
32
110
111
116
32
116
111
32
98
101
Creating Character Arrays From String Objects
public class MainClass {
public static void main(String[] arg) {
String text = "To be or not to be";
char[] textArray = text.toCharArray();
for(char ch: textArray){
System.out.println(ch);
}
}
}
T
o
b
e
o
r
n
o
t
t
o
b
e
Format strings into table
public class Main {
public static void main(String args[]) {
String format = "|%1$-10s|%2$-10s|%3$-20s|\n";
System.out.format(format, "A", "AA", "AAA");
System.out.format(format, "B", "", "BBBBB");
System.out.format(format, "C", "CCCCC", "CCCCCCCC");
String ex[] = { "E", "EEEEEEEEEE", "E" };
System.out.format(String.format(format, (Object[]) ex));
}
}
/*
|A |AA |AAA |
|B | |BBBBB |
|C |CCCCC |CCCCCCCC |
|E |EEEEEEEEEE|E |
*/
Playing with frames(awt and swings)
AWT
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Addition implements ActionListener
{
Frame f;
TextField t1,t2,t3;
Button b;
Label lab1,lab2,lab3;
Addition()
{
f=new Frame("Addition of Two Numbers....umesh gupta");
lab1=new Label();
lab1.setText("Enter the Ist no.");
lab1.setBounds(20,40,100,25);
lab1.setBackground(Color.GRAY);
lab1.setForeground(Color.WHITE);
lab1.setFont(new Font("arial",Font.BOLD,12));
f.add(lab1);
t1=new TextField();
t1.setBounds(150,40,160,25);
t1.setFont(new Font("arial",Font.BOLD,14));
f.add(t1);
lab2=new Label();
lab2.setText("Enter the 2nd no.");
lab2.setBounds(20,120,100,25);
lab2.setBackground(Color.GRAY);
lab2.setForeground(Color.WHITE);
lab2.setFont(new Font("arial",Font.BOLD,12));
f.add(lab2);
t2=new TextField();
t2.setBounds(150,120,160,25);
t2.setFont(new Font("arial",Font.BOLD,14));
f.add(t2);
lab3=new Label();
lab3.setText("Addition");
lab3.setBounds(20,200,100,25);
lab3.setBackground(Color.GRAY);
lab3.setForeground(Color.WHITE);
lab3.setFont(new Font("arial",Font.BOLD,12));
lab3.setAlignment(lab3.CENTER);
f.add(lab3);
t3=new TextField();
t3.setBounds(150,200,160,25);
t3.setFont(new Font("arial",Font.BOLD,14));
f.add(t3);
b=new Button("ADD");
b.setBounds(180,280,60,40);
b.setBackground(Color.BLACK);
b.setForeground(Color.WHITE);
b.setFont(new Font("arial",Font.BOLD,16));
f.add(b);
f.setLayout(null);
f.setSize(400,400);
f.setVisible(true);
b.addActionListener(this);
//b1.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
String s1=t1.getText();
String s2=t2.getText();
int n1=Integer.parseInt(s1);
int n2=Integer.parseInt(s2);
int n3=n1+n2;
t3.setText(String.valueOf(n3));
}
public static void main(String args[])
{
new Addition();
}
}
SWING
JFrame Test
import java.awt.event.*;
import javax.swing.*;
class JFrameTest
{
JFrame f;
JFrameTest()
{
f=new JFrame();
f.setLayout(null);
f.setSize(400,400);
f.setVisible(true);
}
public static void main(String args[])
{
new JFrameTest();
System.out.println("JFRAME WORKS");
}
}
JMenu Test
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MyMenu implements ActionListener
{
JFrame f=new JFrame("Menu is being tested....umesh gupta");
JMenuBar mb;
JMenu m1,m2,m3;
JMenuItem mi1,mi2,mi3;
JRadioButtonMenuItem rb,rb1;
JCheckBoxMenuItem cb,cb1;
MyMenu()
{
mb=new JMenuBar();
m1=new JMenu("First Menu");
m1.setMnemonic(KeyEvent.VK_F);
mb.add(m1);
mi1=new JMenuItem("A text only menu item",KeyEvent.VK_T);
mi1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T,ActionEvent.ALT_MASK));
m1.add(mi1);
//a group of radio button menu items.
m1.addSeparator();
ButtonGroup group=new ButtonGroup();
rb=new JRadioButtonMenuItem("A radio button menu item");
rb.setSelected(true);
rb.setMnemonic(KeyEvent.VK_R);
group.add(rb);
m1.add(rb);
rb1=new JRadioButtonMenuItem("Another one");
rb1.setSelected(true);
rb1.setMnemonic(KeyEvent.VK_O);
group.add(rb1);
m1.add(rb1);
m1.addSeparator();
cb=new JCheckBoxMenuItem("A checkbox menu item");
cb.setMnemonic(KeyEvent.VK_C);
m1.add(cb);
cb1=new JCheckBoxMenuItem("A checkbox menu item");
cb1.setMnemonic(KeyEvent.VK_C);
m1.add(cb1);
m1.addSeparator();
m2=new JMenu("A submenu");
m2.setMnemonic(KeyEvent.VK_S);
mi2=new JMenuItem("An item in the submenu");
mi2.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_2,ActionEvent.ALT_MASK));
m2.add(mi2);
m1.add(m2);
mi3=new JMenuItem("exit");
mi3.addActionListener(this);
m1.add(mi3);
//Build second menu in menu bar.
m3=new JMenu("Another menu");
m3.setMnemonic(KeyEvent.VK_N);
mb.add(m3);
f.setJMenuBar(mb);
f.setSize(300,400);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("exit"))
System.exit(0);
}
public static void main(String args[])
{
new MyMenu();
}
}
JTree Test
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;
class MyTree// extends MouseAdapter
{
JFrame f;
JTree t;
JScrollPane sp;
MyTree()
{
f=new JFrame("JTree is being tested....umesh gupta");
DefaultMutableTreeNode root=new DefaultMutableTreeNode("style");
DefaultMutableTreeNode color=new DefaultMutableTreeNode("color");
DefaultMutableTreeNode font=new DefaultMutableTreeNode("font");
root.add(color);
root.add(font);
DefaultMutableTreeNode red=new DefaultMutableTreeNode("red");
DefaultMutableTreeNode green=new DefaultMutableTreeNode("green");
DefaultMutableTreeNode blue=new DefaultMutableTreeNode("blue");
color.add(red);
color.add(green);
color.add(blue);
DefaultMutableTreeNode bold=new DefaultMutableTreeNode("bold");
DefaultMutableTreeNode italic=new DefaultMutableTreeNode("italic");
DefaultMutableTreeNode un=new DefaultMutableTreeNode("un");
font.add(bold);
font.add(italic);
font.add(un);
t=new JTree(root);
//t.addMouseListener(this);
sp=new JScrollPane(t);
f.add(sp);
f.setSize(400,400);
f.setVisible(true);
}
/*public void mouseClicked(MouseListener e)
{
System.out.println("bold");
}*/
public static void main(String args[])
{
new MyTree();
}
}
Database
import java.sql.*;
public class SelectApp {
public static void main(String args[]) {
String url = "jdbc:msql://athens.imaginary.com:4333/db_web";
try {
Class.forName("imaginary.sql.iMsqlDriver");
}
catch( Exception e ) {
System.out.println("Failed to load mSQL driver.");
return;
}
try {
Connection con = DriverManager.getConnection(url, "borg", "");
Statement select = con.createStatement();
ResultSet result = select.executeQuery
("SELECT key, val FROM t_test");
System.out.println("Got results:");
while(result.next()) { // process results one row at a time
int key = result.getInt(1);
String val = result.getString(2);
System.out.println("key = " + key);
System.out.println("val = " + val);
}
select.close();
con.close();
}
catch( Exception e ) {
e.printStackTrace();
}
}
}
Applets
Both.html
Testapplet6.java
/*
*/
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import java.net.*;
public class TestApplet6 extends Applet implements ActionListener
{
Button b;
public void init()
{
setBackground(Color.blue);
b=new Button("okay");
add(b);
b.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
AppletContext ac=getAppletContext();
Applet a=ac.getApplet("app2");
a.setBackground(Color.GREEN);
}
}
Used.java
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class Used extends Applet
{
public void init()
{
setBackground(Color.RED);
}
}
Garbage Collection
System.runFinalization();
System.gc();
finalize x;
Major application markets
Health Care(NOMICE,MASKIT,iHEALTH)
Banking(FINACLE,OSI)
Telecom(NSN)
Resource Management
Consultancy
Support
Share Market
Security
MVC