java by dandanhuanghuang

VIEWS: 17 PAGES: 46

									                                 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 < 5; i++) {
          System.out.println(i + " ");
      }
    }
}
public class WHILEMainClass {

    public static void main(String[] args) {
      int i = 0;
      while (i < 3) {
        System.out.println(i);
        i++;
      }
    }

}
How concepts are implemented
Class and object concepts
public class MainClass
{
   public static void main( String args[] )
   {
      GradeBook myGradeBook = new GradeBook();

        myGradeBook.displayMessage();
    }
}
class GradeBook
{
   public void displayMessage()
   {
      System.out.println( "Welcome to the Grade Book!" );
   }

}
Constructor concepts
public class MainClass
{
   public static void main( String args[] )
   {
       Sphere sphere = new Sphere();
       Sphere sphere = new Sphere(4);
   }
}
class Sphere
{
  int radius = 0;
  Sphere() {
     radius = 1;
  }
  Sphere(int radius) {
     //this();
     this.radius = radius;
  }
}
Object instance
class Number {
   int i;
}
public class MainClass {
   public static void main(String[] args) {
      Number n1 = new Number();
      Number n2 = new Number();
      n1.i = 9;
      n2.i = 47;
      System.out.println("1: n1.i: " + n1.i + ", n2.i: " + n2.i);
      n1 = n2;
      System.out.println("2: n1.i: " + n1.i + ", n2.i: " + n2.i);
      n1.i = 27;
      System.out.println("3: n1.i: " + n1.i + ", n2.i: " + n2.i);
   }
}
1: n1.i: 9, n2.i: 47                               .
2: n1.i: 47, n2.i: 47                              .
3: n1.i: 27, n2.i: 27                              .
class Dog{
   public Dog(String aType){
   }
}
public class MainClass{
   public static void main(String[] a){
      Dog d = new Dog("a");
      Class objectType = d.getClass();
      System.out.println(objectType.getName());
   }
}
Dog                   .
Inheritance
//The Parent class
public class Parent {
     }

//The Child class
public class Child extends Parent {
     }



EXAMPLE
public class P {
  public void publicMethod() {
  }
  protected void protectedMethod() {
  }
  void defaultMethod() {
  }
}
class C extends P {
  public void testMethod() {
    publicMethod();
    protectedMethod();
    defaultMethod();
  }
}
class Animal {
  public Animal(String aType) {
    type = aType;
  }
  public String toString() {
    return "This is a " + type;
  }
  private String type;
}
class Dog extends Animal {
  public Dog(String name){
    super(name);
  }
  private String breed;
}
class A {
  char doh(char c) {
    System.out.println("doh(char)");
    return 'd';
  }
  float doh(float f) {
    System.out.println("doh(float)");
    return 1.0f;
  }
}

class B {}

class C extends A {
  void doh(B m) {
    System.out.println("doh(B)");
  }
}

public class MainClass {
  public static void main(String[] args) {
    C b = new C();
    b.doh(1);
    b.doh('x');
    b.doh(1.0f);
    b.doh(new B());
  }
}

doh(float)
doh(char)
doh(float)
doh(B)
Abstraction
abstract class A {
  abstract void callme();
  void callmetoo() {
     System.out.println("This is a concrete method.");
  }}
class B extends A {
  void callme() {
     System.out.println("B's implementation of callme.");
  }}
class AbstractDemo {
  public static void main(String args[]) {
     B b = new B();
     b.callme();
     b.callmetoo();
  }}
Interface
interface ThisInterface {
  public void thisMethod();
}
interface ThatInterface {
  public void thatMethod();
}
class MyClass implements ThisInterface, ThatInterface {
  // Class definition including methods from both interfaces...
  public void thisMethod() {
    System.out.println("this");
  }
  public void thatMethod() {
    System.out.println("that");
  }
}
public class MainClass {
  public static void main(String[] a) {
    MyClass cls = new MyClass();
    cls.thisMethod();
    cls.thatMethod();
  }
}
Polymorphism
class Employee {
  public void work() {
    System.out.println("I am an employee.");
  }
}

class Manager extends Employee {
  public void work() {
    System.out.println("I am a manager.");
  }

    public void manage() {
      System.out.println("Managing ...");
    }
}

public class PolymorphismTest1 {
  public static void main(String[] args) {
    Employee employee;
    employee = new Manager();
    System.out.println(employee.getClass().getName());
    employee.work();
    Manager manager = (Manager) employee;
    manager.manage();
  }
}
Constructors and polymorphism don't produce what you might expect

abstract class Glyph {
  abstract void draw();

    Glyph() {
      System.out.println("Glyph() before draw()");
      draw();
      System.out.println("Glyph() after draw()");
    }
}

class RoundGlyph extends Glyph {
  private int radius = 1;

    RoundGlyph(int r) {
      radius = r;
      System.out.println("RoundGlyph.RoundGlyph(), radius = " + radius);
    }

    void draw() {
      System.out.println("RoundGlyph.draw(), radius = " + radius);
    }
}

public class MainClass {
  public static void main(String[] args) {
    new RoundGlyph(5);
  }
}

Glyph() before draw()
RoundGlyph.draw(), radius = 0
Glyph() after draw()
RoundGlyph.RoundGlyph(), radius = 5


Enumerations
enum Week {
  Monday, Tuesday, Wednesday, Thursday, Friday, Saturaday, Sunday
}

public class MainClass {
  public static void main(String args[]) {
    Week aWeekDay;

        aWeekDay = Week.Monday;

        // Output an enum value.
        System.out.println("Value of aWeekDay: " + aWeekDay);
        System.out.println();
    }
}

Value of aWeekDay: Monday
Collections
The framework consists of four core interfaces with two specializations for sorting
   1. Collection
   2. Stack
   3. Queue
   4. List
   5. Set
   6. Map
   7. SortedSet
   8. SortedMap

import     java.util.ArrayList;
import     java.util.Collection;
import     java.util.Collections;
import     java.util.HashMap;
import     java.util.HashSet;
import     java.util.List;
import     java.util.Map;
import     java.util.Set;
import     java.util.Stack;
import     java.util.Queue;


Sort elements of ArrayList

  Adding a single element to the list by calling the add() method:
  public boolean add(Object element)

  public boolean add(int index, Object element)

  import java.util.ArrayList;
  import java.util.List;

  public class MainClass {
    public static void main(String args[]) throws Exception {
      // Create/fill collection
      List list = new ArrayList();
      list.add("A");
      list.add("B");
      list.add("C");
      System.out.println(list);
    }
  }

  [A, B, C]
Adding Another Collection

public boolean addAll(Collection c)
public boolean addAll(int index, Collection c)

import java.util.Vector;
public class MainClass {
  public static void main(String args[]) {
    Vector v = new Vector(5);
    for (int i = 0; i < 10; i++) {
      v.insertElementAt(i,0);
    }
    System.out.println(v);
    Vector v2 = new Vector();
    v2.addAll(v);
    v2.addAll(v);
    System.out.println(v2);
  }
}

[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 9, 8, 7, 6, 5, 4, 3, 2, 1,
0]

Convert a List to a Set
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Main {
  public static void main(String[] args) {
    List<String> myList = new ArrayList<String>();
    myList.add("A");
    myList.add("B");
    myList.add("C");
    myList.add("D");
    Set<String> mySet = new HashSet<String>(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<String> myQueue = new LinkedList<String>();
    myQueue.add("A");
    myQueue.add("B");
    myQueue.add("C");
    myQueue.add("D");

         List<String> myList = new ArrayList<String>(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> {
  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<Integer> iOb = new GenericClass<Integer>(88);
    iOb.showType();
    // no cast is needed.
    int v = iOb.getob();
    System.out.println("value: " + v);
    // Create a Gen object for Strings.
    GenericClass<String> strOb = new GenericClass<String>("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<int> strOb = new Gen<int>(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<String> stringList2 = new ArrayList<String>();
        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<Person> {
    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 <T, V extends T> boolean isIn(T x, V[] y) {
    for (int i = 0; i < y.length; i++){
      if (x.equals(y[i])){
        return true;
      }
    }
    return false;
  }

    public static void main(String args[]) {
      Integer nums[] = { 1, 2, 3, 4, 5 };

        if (isIn(2, nums)){
          System.out.println("2 is in nums");
        }
        if (!isIn(7, nums)){
          System.out.println("7 is not in nums");
        }

        // Use isIn() on Strings.
        String strs[] = { "one", "two", "three", "four", "five" };

        if (isIn("two", strs))
          System.out.println("two is in strs");

        if (!isIn("seven", strs))
          System.out.println("seven is not in strs");

    }
}

2 is in nums
7 is not in nums
two is in strs
seven is not in strs
Defining a Generic Class Type
import java.awt.Point;
class ListItem {
  public ListItem(Object item) {
    this.item = item;
    next = null;
  }
  public String toString() {
    return "ListItem " + item;
  }

    ListItem next;

    Object item;
}

class LinkedList<T> {
  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 < items.length; i++) {
              addItem(items[i]);
            }
            current = start;
        }
    }

    public void addItem(T item) {
      ListItem newEnd = new ListItem(item);
      if (start == null) {
        start = end = newEnd;
      } else {
        end.next = newEnd;
        end = newEnd;
      }
    }

    public T getFirst() {
      current = start;
      return start == null ? null : start.item;
    }

    public T getNext() {
      if (current != null) {
        current = current.next;
      }
      return current == null ? null : current.item;
    }

    private ListItem start = null;
    private ListItem end = null;

    private ListItem current = null;

    private class ListItem {

        public ListItem(T item) {
          this.item = item;
          next = null;
        }

        public String toString() {
          return "ListItem " + item;
        }

        ListItem next;

        T item;
    }
}

public class MainClass {
  public static void main(String[] a) {

        LinkedList<Point> polyline = new LinkedList<Point>();

        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<Object> list = new ArrayList<Object>();
    list.add(p);
    list.add(a);
    list.add(t);
    list.add(text);
    list.add(number);
    for (int i = 0; i < list.size(); i++) {
      Object o = list.get(i);
      if (o instanceof Person) {
        System.out.println("My name is " + ((Person) o).getName());
      } else if (o instanceof Animal) {
        System.out.println("I live in " + ((Animal) o).getHabitat());
      } else if (o instanceof Thing) {
        System.out.println("My color is " + ((Thing) o).getColor());
      } else if (o instanceof String) {
        System.out.println("My text is " + o.toString());
      } else if (o instanceof Integer) {
        System.out.println("My value is " + ((Integer) o));
      }
    }
  }
}

class Person {
  private String name;
  public Person(String name) {
    this.name = name;
  }
  public String getName() {
    return name;
  }
}
class Animal {
  private String habitat;
  public Animal(String habitat) {
    this.habitat = habitat;
  }
  public String getHabitat() {
    return habitat;
  }
}
class Thing {
  private String color;

  public Thing(String color) {
    this.color = color;
  }
  public String getColor() {
    return color;
  }
FileInputStream

  1. The FileInputStream class is a subclass of InputStream.
  2. The FileInputStream class allows you to read binary data sequentially from a file.
  3. The FileInputStream class's constructors allow you to pass either a File object or a path to a file.

public FileInputStream (String path)
public FileInputStream (File file)

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class MainClass {
  public static void main(String[] args) {
    boolean areFilesIdentical = true;
    File file1 = new File("c:\\file1.txt");
    File file2 = new File("c:\\file2.txt");
    if (!file1.exists() || !file2.exists()) {
      System.out.println("One or both files do not exist");
      System.out.println(false);
    }
    System.out.println("length:" + file1.length());
    if (file1.length() != file2.length()) {
      System.out.println("lengths not equal");
      System.out.println(false);
    }
    try {
      FileInputStream fis1 = new FileInputStream(file1);
      FileInputStream fis2 = new FileInputStream(file2);
      int i1 = fis1.read();
      int i2 = fis2.read();
      while (i1 != -1) {
        if (i1 != i2) {
          areFilesIdentical = false;
          break;
        }
        i1 = fis1.read();
        i2 = fis2.read();
      }
      fis1.close();
      fis2.close();
    } catch (IOException e) {
      System.out.println("IO exception");
      areFilesIdentical = false;
    }
    System.out.println(areFilesIdentical);
  }
}
FileReader

   1. The FileReader class is a subclass of InputStreamReader
   2. The FileReader class is a convenient class to read characters from a file.
   3. The FileReader class uses an encoding other than the default one.

To construct a FileReader object:
public FileReader (File file)
public FileReader (FileDescriptor fileDescriptor)
public FileReader (String filePath)


FileWriter

   1. FileWriter provides a convenient way of writing characters to a file.
   2. FileWriter uses your computer's default character encoding.

public FileWriter (File file)
public FileWriter (File file, boolean append)

public FileWriter (String path)
public FileWriter (String path, boolean append)
public FileWriter (FileDescriptor fileDescriptor)


BufferedReader

   1. BufferedReader wraps another Reader and improves performance.
   2. BufferedReader provides a readLine method to read a line of text.

Using BufferedReader:
InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream (textFile), enc
BufferedReader bufferedReader = new BufferedReader (inputStreamReader);


BufferedWriter

You can rap your Writer with a BufferedWriter for better performance. BufferedWriter has the following constructors:
public BufferedWriter (Writer writer)
public BufferedWriter (Writer writer, in bufferSize)

Wrap FileWriter in a BufferedWriter:
FileWriter fw = new FileWriter(aFile);
BufferedWriter bw = new BufferedWriter (fw);

Wrap the Writer to a PrintWriter.
FileWriter fw = new FileWriter (aFile);
PrintWriter pw = new PrintWriter (new BufferedWriter(fw));
String
public class Main {
  public static void main(String[] args) {
    String name = "Java";
    int length = name.length();

    System.out.println("Length = " + length+” ”+name.toUpperCase());


         String s1 = "Java";
         String s2 = "Java";
         if (s1.equals(s2)) {
           System.out.println("==");
         }
    }
}
Split a String

public class Main {
  public static void main(String[] args) {
    String str = "one,two,three,four,five";

        String[] elements = str.split(",");
        for (int i = 0; i < elements.length; i++)
          System.out.println(elements[i]);
   }
}
/*
one
two
three
four
five
*/

Get the difference between two strings
public class Utils {
  public static String diff(String str1, String str2) {
    int index = str1.lastIndexOf(str2);
    if (index > -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
<html>
<applet code="TestApplet6.class" name="app1" height=400 width=400>
</applet>

<applet code="Used.class" name="app2" height=400 width=400>
</applet>
</html>
Testapplet6.java
/*
<applet code="TestApplet5.class" height=400 width=400>
<param name="image" value="1.jpg">
</applet>
*/

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

								
To top