Вы находитесь на странице: 1из 39

ENCAPSULATION PROGRAM

package oopsconcept;
public class Mobile {
private String manufacturer;
private String operating_system;
public String model;
private int cost;
//Constructor to set properties/characteristics of object
Mobile(String man, String o,String m, int c){
this.manufacturer = man;
this.operating_system=o;
this.model=m;
this.cost=c;
}
//Method to get access Model property of Object
public String getModel(){
return this.model;
}
// We can add other method to get access to other properties
}

INHERITANCE PROGRAM
package oopsconcept;
public class Android extends Mobile{
//Constructor to set properties/characteristics of object
Android(String man, String o,String m, int c){
super(man, o, m, c);
}
//Method to get access Model property of Object
public String getModel(){
return "This is Android Mobile- " + model;
}
}
package oopsconcept;
public class Blackberry extends Mobile{
//Constructor to set properties/characteristics of object
Blackberry(String man, String o,String m, int c){
super(man, o, m, c);
}
public String getModel(){
return "This is Blackberry-"+ model;
}
}

POLYMORPHISM PROGRAM
package oopsconcept;
class Overloadsample {
public void print(String s){
System.out.println("First Method with only String- "+ s);
}
public void print (int i){
System.out.println("Second Method with only int- "+ i);
}
public void print (String s, int i){
System.out.println("Third Method with both- "+ s + "--" + i);
}
}
public class PolymDemo {
public static void main(String[] args) {
Overloadsample obj = new Overloadsample();
obj.print(10);
obj.print("Amit");
obj.print("Hello", 100);
}
}

Example of a constructor
public class Puppy{
public Puppy(){
}

public Puppy(String name){


// This constructor has one parameter, name.
}
}

Example of creating an object


public class Puppy{

public Puppy(String name){


// This constructor has one parameter, name.
System.out.println("Passed Name is :" + name );
}
public static void main(String []args){
// Following statement would create an object myPuppy
Puppy myPuppy = new Puppy( "tommy" );
}
}

access instance variables and methods of a class


public class Puppy{
int puppyAge;

public Puppy(String name){


// This constructor has one parameter, name.
System.out.println("Passed Name is :" + name );
}
public void setAge( int age ){
puppyAge = age;
}

public int getAge( ){


System.out.println("Puppy's age is :" + puppyAge );
return puppyAge;
}
public static void main(String []args){
/* Object creation */
Puppy myPuppy = new Puppy( "tommy" );

/* Call class method to set puppy's age */


myPuppy.setAge( 2 );

/* Call another class method to get puppy's age */


myPuppy.getAge( );

/* You can access instance variable as follows as well */


System.out.println("Variable Value :" + myPuppy.puppyAge );
}
}

If we compile and run the above program, then it would produce the following result:

Passed Name is :tommy


Puppy's age is :2
Variable Value :2

create, initialize and process arrays


public class TestArray {

public static void main(String[] args) {


double[] myList = {1.9, 2.9, 3.4, 3.5};

// Print all the array elements


for (int i = 0; i < myList.length; i++) {
System.out.println(myList[i] + " ");
}
// Summing all elements
double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
System.out.println("Total is " + total);
// Finding the largest element
double max = myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}
}

This would produce the following result:

1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5

How to create a basic Applet?

import java.applet.*;

import java.awt.*;

public class Main extends Applet{

public void paint(Graphics g){

g.drawString("Welcome in Java Applet.",40,20);

Now compile the above code and call the generated class in your HTML code as follows:

<HTML>

<HEAD>

</HEAD>
<BODY>

<div >

<APPLET CODE="Main.class" WIDTH="800" HEIGHT="500">

</APPLET>

</div>

</BODY>

</HTML>

Result:
The above code sample will produce the following result in a java enabled web browser.

Welcome in Java Applet.

Event Handling
import java.awt.event.MouseListener;

import java.awt.event.MouseEvent;

import java.applet.Applet;

import java.awt.Graphics;

public class ExampleEventHandling extends Applet

implements MouseListener {

StringBuffer strBuffer;

public void init() {

addMouseListener(this);

strBuffer = new StringBuffer();

addItem("initializing the apple ");

public void start() {


addItem("starting the applet ");

public void stop() {

addItem("stopping the applet ");

public void destroy() {

addItem("unloading the applet");

void addItem(String word) {

System.out.println(word);

strBuffer.append(word);

repaint();

public void paint(Graphics g) {

//Draw a Rectangle around the applet's display area.

g.drawRect(0, 0,

getWidth() - 1,

getHeight() - 1);

//display the string inside the rectangle.

g.drawString(strBuffer.toString(), 10, 20);

public void mouseEntered(MouseEvent event) {

public void mouseExited(MouseEvent event) {

public void mousePressed(MouseEvent event) {


}

public void mouseReleased(MouseEvent event) {

public void mouseClicked(MouseEvent event) {

addItem("mouse clicked! ");

<html>

<title>Event Handling</title>

<hr>

<applet code="ExampleEventHandling.class"

width="300" height="300">

</applet>

<hr>

</html>

THREAD
class RunnableThread implements Runnable {

Thread runner;
public RunnableThread() {
}
public RunnableThread(String threadName) {
runner = new Thread(this, threadName); // (1) Create a new thread.
System.out.println(runner.getName());
runner.start(); // (2) Start the thread.
}
public void run() {
//Display info about this particular thread
System.out.println(Thread.currentThread());
}
}

public class RunnableExample {

public static void main(String[] args) {


Thread thread1 = new Thread(new RunnableThread(), "thread1");
Thread thread2 = new Thread(new RunnableThread(), "thread2");
RunnableThread thread3 = new RunnableThread("thread3");
//Start the threads
thread1.start();
thread2.start();
try {
//delay for one second
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
}
//Display info about the main thread
System.out.println(Thread.currentThread());
}
}

EXTENDING THREAD CLASS

class XThread extends Thread {

XThread() {
}
XThread(String threadName) {
super(threadName); // Initialize thread.
System.out.println(this);
start();
}
public void run() {
//Display info about this particular thread
System.out.println(Thread.currentThread().getName());
}
}

public class ThreadExample {

public static void main(String[] args) {


Thread thread1 = new Thread(new XThread(), "thread1");
Thread thread2 = new Thread(new XThread(), "thread2");
// The below 2 threads are assigned default names
Thread thread3 = new XThread();
Thread thread4 = new XThread();
Thread thread5 = new XThread("thread5");
//Start the threads
thread1.start();
thread2.start();
thread3.start();
thread4.start();
try {
//The sleep() method is invoked on the main thread to cause a one second delay.
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
}
//Display info about the main thread
System.out.println(Thread.currentThread());
}
}

MULTITHREADING
class RunnableDemo implements Runnable {
private Thread t;

private String threadName;

RunnableDemo( String name){

threadName = name;

System.out.println("Creating " + threadName );

public void run() {

System.out.println("Running " + threadName );

try {

for(int i = 4; i > 0; i--) {

System.out.println("Thread: " + threadName + ", " + i);

// Let the thread sleep for a while.

Thread.sleep(50);

} catch (InterruptedException e) {

System.out.println("Thread " + threadName + " interrupted.");

System.out.println("Thread " + threadName + " exiting.");

public void start ()

System.out.println("Starting " + threadName );

if (t == null)

t = new Thread (this, threadName);

t.start ();

public class TestThread {

public static void main(String args[]) {

RunnableDemo R1 = new RunnableDemo( "Thread-1");

R1.start();

RunnableDemo R2 = new RunnableDemo( "Thread-2");

R2.start();

}
This would produce the following result:

Creating Thread-1

Starting Thread-1

Creating Thread-2

Starting Thread-2

Running Thread-1

Thread: Thread-1, 4

Running Thread-2

Thread: Thread-2, 4

Thread: Thread-1, 3

Thread: Thread-2, 3

Thread: Thread-1, 2

Thread: Thread-2, 2

Thread: Thread-1, 1

Thread: Thread-2, 1

Thread Thread-1 exiting.

Thread Thread-2 exiting

Multithreading example with Synchronization:

class PrintDemo {

public void printCount(){

try {

for(int i = 5; i > 0; i--) {

System.out.println("Counter --- " + i );

} catch (Exception e) {

System.out.println("Thread interrupted.");

class ThreadDemo extends Thread {

private Thread t;

private String threadName;

PrintDemo PD;

ThreadDemo( String name, PrintDemo pd){

threadName = name;
PD = pd;

public void run() {

synchronized(PD) {

PD.printCount();

System.out.println("Thread " + threadName + " exiting.");

public void start ()

System.out.println("Starting " + threadName );

if (t == null)

t = new Thread (this, threadName);

t.start ();

public class TestThread {

public static void main(String args[]) {

PrintDemo PD = new PrintDemo();

ThreadDemo T1 = new ThreadDemo( "Thread - 1 ", PD );

ThreadDemo T2 = new ThreadDemo( "Thread - 2 ", PD );

T1.start();

T2.start();

// wait for threads to end

try {

T1.join();

T2.join();

} catch( Exception e) {

System.out.println("Interrupted");

This produces same result every time you run this program:
Starting Thread - 1

Starting Thread - 2

Counter --- 5

Counter --- 4

Counter --- 3

Counter --- 2

Counter --- 1

Thread Thread - 1 exiting.

Counter --- 5

Counter --- 4

Counter --- 3

Counter --- 2

Counter --- 1

Thread Thread - 2 exiting.

Byte/Character Stream
import java.io.*;

public class CopyFile {


public static void main(String args[]) throws IOException
{
FileInputStream in = null;
FileOutputStream out = null;

try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");

int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}

Character Streams
import java.io.*;

public class CopyFile {


public static void main(String args[]) throws IOException
{
FileReader in = null;
FileWriter out = null;

try {
in = new FileReader("input.txt");
out = new FileWriter("output.txt");

int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}

java.io.BufferedReader.read() method
package com.tutorialspoint;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;

public class BufferedReaderDemo {


public static void main(String[] args) throws Exception {

InputStream is = null;
InputStreamReader isr = null;
BufferedReader br = null;

try{
// open input stream test.txt for reading purpose.
is = new FileInputStream("c:/test.txt");

// create new input stream reader


isr = new InputStreamReader(is);

// create new buffered reader


br = new BufferedReader(isr);
int value=0;

// reads to the end of the stream


while((value = br.read()) != -1)
{
// converts int to character
char c = (char)value;

// prints character
System.out.println(c);
}

}catch(Exception e){
e.printStackTrace();
}finally{

// releases resources associated with the streams


if(is!=null)
is.close();
if(isr!=null)
isr.close();
if(br!=null)
br.close();
}
}
}

Buffered Writer
package com.tutorialspoint;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.StringWriter;

public class BufferedWriterDemo {


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

StringWriter sw = null;
BufferedWriter bw = null;

String str = "Hello World!";

try{
// create string writer
sw = new StringWriter();

//create buffered writer


bw = new BufferedWriter(sw);

// writing string to writer


bw.write(str);

// forces out the characters to string writer


bw.flush();

// string buffer is created


StringBuffer sb = sw.getBuffer();

//prints the string


System.out.println(sb);

}catch(IOException e){
// if I/O error occurs
e.printStackTrace();
}finally{
// releases any system resources associated with the stream
if(sw!=null)
sw.close();
if(bw!=null)
bw.close();
}
}
}

AWTGraphicsDemo.java
package com.tutorialspoint.gui;

import java.awt.*;

import java.awt.event.*;

import java.awt.geom.*;

public class AWTGraphicsDemo extends Frame {

public AWTGraphicsDemo(){

super("Java AWT Examples");

prepareGUI();

public static void main(String[] args){

AWTGraphicsDemo awtGraphicsDemo = new AWTGraphicsDemo();

awtGraphicsDemo.setVisible(true);

private void prepareGUI(){

setSize(400,400);
addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent windowEvent){

System.exit(0);

});

@Override

public void paint(Graphics g) {

g.setColor(Color.GRAY);

Font font = new Font("Serif", Font.PLAIN, 24);

g.setFont(font);

g.drawString("Welcome to TutorialsPoint", 50, 150);

Panel Example
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtContainerDemo {


private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;
private Label msglabel;
public AwtContainerDemo(){
prepareGUI();
}

public static void main(String[] args){


AwtContainerDemo awtContainerDemo = new
AwtContainerDemo();
awtContainerDemo.showPanelDemo();
}

private void prepareGUI(){


mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent windowEvent){


System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);

msglabel = new Label();


msglabel.setAlignment(Label.CENTER);
msglabel.setText("Welcome to TutorialsPoint AWT Tutorial.");

controlPanel = new Panel();


controlPanel.setLayout(new FlowLayout());

mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}

private void showPanelDemo(){


headerLabel.setText("Container in action: Panel");

Panel panel = new Panel();


panel.setBackground(Color.magenta);
panel.setLayout(new FlowLayout());
panel.add(msglabel);
controlPanel.add(panel);

mainFrame.setVisible(true);
}
}

Frame Example

package com.tutorialspoint.gui;

import java.awt.*;

import java.awt.event.*;

public class AwtContainerDemo {

private Frame mainFrame;

private Label headerLabel;

private Label statusLabel;

private Panel controlPanel;

private Label msglabel;

public AwtContainerDemo(){

prepareGUI();

public static void main(String[] args){

AwtContainerDemo awtContainerDemo = new AwtContainerDemo();

awtContainerDemo.showFrameDemo();

private void prepareGUI(){

mainFrame = new Frame("Java AWT Examples");

mainFrame.setSize(400,400);

mainFrame.setLayout(new GridLayout(3, 1));

mainFrame.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent windowEvent){


System.exit(0);

});

headerLabel = new Label();

headerLabel.setAlignment(Label.CENTER);

statusLabel = new Label();

statusLabel.setAlignment(Label.CENTER);

statusLabel.setSize(350,100);

msglabel = new Label();

msglabel.setAlignment(Label.CENTER);

msglabel.setText("Welcome to TutorialsPoint AWT Tutorial.");

controlPanel = new Panel();

controlPanel.setLayout(new FlowLayout());

mainFrame.add(headerLabel);

mainFrame.add(controlPanel);

mainFrame.add(statusLabel);

mainFrame.setVisible(true);

private void showFrameDemo(){

headerLabel.setText("Container in action: Frame");

final Frame frame = new Frame();

frame.setSize(300, 300);

frame.setLayout(new FlowLayout());

frame.add(msglabel);

frame.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent windowEvent){

frame.dispose();

});

Button okButton = new Button("Open a Frame");

okButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

statusLabel.setText("A Frame shown to the user.");

frame.setVisible(true);

});

controlPanel.add(okButton);
mainFrame.setVisible(true);

MAIN PROGRAM FOR AWT


import java.awt.*;
class AWTPanel extends Frame
{
Panel panel;
Button b1,b2;
public AWTPanel()
{

// Set frame properties


setTitle("AWT Panel"); // Set the title
setSize(400,400); // Set size to the frame
setLayout(new FlowLayout()); // Set the
layout
setVisible(true); // Make the frame visible
setLocationRelativeTo(null); // Center the
frame

// Create the panel


panel=new Panel();

// Set panel background


panel.setBackground(Color.gray);

// Create buttons
b1=new Button(); // Create a button with
default constructor
b1.setLabel("I am button 1"); // Set the
text for button

b2=new Button("Button 2"); // Create a


button with sample text
b2.setBackground(Color.lightGray); // Set
the background to the button

// Add the buttons to the panel


panel.add(b1);
panel.add(b2);

// Add the panel to the frame


add(panel);

}
public static void main(String args[])
{
new AWTPanel();
}
}

Container
package com.javacodegeeks.snippets.desktop;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Component;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.TextArea;

public class CreateContainerExample {

public static void main(String[] args) {

// Create a frame
Frame frame = new Frame("Example Frame");

/*

* Create a container with a flow layout, which


arranges its children

* horizontally and center aligned.

* A container can also be created with a


specific layout using

* Panel(LayoutManager) constructor, e.g.

* Panel(new FlowLayout(FlowLayout.RIGHT)) for


right alignment

*/
Panel panel = new Panel();

// Add several buttons to the container


panel.add(new Button("Button_A"));
panel.add(new Button("Button_B"));
panel.add(new Button("Button_C"));

// Add a text area in the center of the


frame
Component textArea = new
TextArea("This is a sample text...");
frame.add(textArea,
BorderLayout.CENTER);

// Add the container to the bottom


of the frame
frame.add(panel,
BorderLayout.SOUTH);

// Display the frame


int frameWidth = 300;
int frameHeight = 300;
frame.setSize(frameWidth,
frameHeight);

frame.setVisible(true);
}

}
Creating JDBC Application

//STEP 1. Import required packages

import java.sql.*;

public class FirstExample {

// JDBC driver name and database URL

static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";

static final String DB_URL = "jdbc:mysql://localhost/EMP";

// Database credentials

static final String USER = "username";

static final String PASS = "password";

public static void main(String[] args) {

Connection conn = null;

Statement stmt = null;

try{

//STEP 2: Register JDBC driver

Class.forName("com.mysql.jdbc.Driver");

//STEP 3: Open a connection

System.out.println("Connecting to database...");

conn = DriverManager.getConnection(DB_URL,USER,PASS);

//STEP 4: Execute a query

System.out.println("Creating statement...");

stmt = conn.createStatement();

String sql;

sql = "SELECT id, first, last, age FROM Employees";

ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set

while(rs.next()){

//Retrieve by column name

int id = rs.getInt("id");

int age = rs.getInt("age");

String first = rs.getString("first");

String last = rs.getString("last");

//Display values

System.out.print("ID: " + id);

System.out.print(", Age: " + age);

System.out.print(", First: " + first);

System.out.println(", Last: " + last);

//STEP 6: Clean-up environment

rs.close();

stmt.close();

conn.close();

}catch(SQLException se){

//Handle errors for JDBC

se.printStackTrace();

}catch(Exception e){

//Handle errors for Class.forName

e.printStackTrace();

}finally{

//finally block used to close resources

try{

if(stmt!=null)

stmt.close();

}catch(SQLException se2){

}// nothing we can do

try{

if(conn!=null)
conn.close();

}catch(SQLException se){

se.printStackTrace();

}//end finally try

}//end try

System.out.println("Goodbye!");

}//end main

}//end FirstExample

Why Use Generics?


In a nutshell, generics enable types (classes and interfaces) to be parameters when defining classes,
interfaces and methods. Much like the more familiar formal parameters used in method declarations, type
parameters provide a way for you to re-use the same code with different inputs. The difference is that the
inputs to formal parameters are values, while the inputs to type parameters are types.

Code that uses generics has many benefits over non-generic code:

 Stronger type checks at compile time.


A Java compiler applies strong type checking to generic code and issues errors if the code violates
type safety. Fixing compile-time errors is easier than fixing runtime errors, which can be difficult to
find.

 Elimination of casts.
The following code snippet without generics requires casting:
 List list = new ArrayList();
 list.add("hello");
 String s = (String) list.get(0);

When re-written to use generics, the code does not require casting:

List<String> list = new ArrayList<String>();


list.add("hello");
String s = list.get(0); // no cast

 Enabling programmers to implement generic algorithms.


By using generics, programmers can implement generic algorithms that work on collections of
different types, can be customized, and are type safe and easier to read.
Generic Classes:
A generic class declaration looks like a non-generic class declaration, except that the class name is
followed by a type parameter section.

As with generic methods, the type parameter section of a generic class can have one or more type
parameters separated by commas. These classes are known as parameterized classes or
parameterized types because they accept one or more parameters.

Example:
Following example illustrates how we can define a generic class:

public class Box<T> {

private T t;

public void add(T t) {

this.t = t;

public T get() {

return t;

public static void main(String[] args) {

Box<Integer> integerBox = new Box<Integer>();

Box<String> stringBox = new Box<String>();

integerBox.add(new Integer(10));

stringBox.add(new String("Hello World"));

System.out.printf("Integer Value :%d\n\n", integerBox.get());

System.out.printf("String Value :%s\n", stringBox.get());

}
}

This would produce the following result:

Integer Value :10

String Value :Hello World

Generic Methods:
You can write a single generic method declaration that can be called with arguments of different
types. Based on the types of the arguments passed to the generic method, the compiler handles
each method call appropriately. Following are the rules to define Generic Methods:

 All generic method declarations have a type parameter section delimited by angle brackets
(< and >) that precedes the method's return type ( < E > in the next example).

 Each type parameter section contains one or more type parameters separated by commas.
A type parameter, also known as a type variable, is an identifier that specifies a generic
type name.

 The type parameters can be used to declare the return type and act as placeholders for the
types of the arguments passed to the generic method, which are known as actual type
arguments.

 A generic method's body is declared like that of any other method. Note that type
parameters can represent only reference types, not primitive types (like int, double and
char).

Example:
Following example illustrates how we can print array of different type using a single Generic
method:

public class GenericMethodTest

// generic method printArray

public static < E > void printArray( E[] inputArray )

// Display array elements


for ( E element : inputArray ){

System.out.printf( "%s ", element );

System.out.println();

public static void main( String args[] )

// Create arrays of Integer, Double and Character

Integer[] intArray = { 1, 2, 3, 4, 5 };

Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 };

Character[] charArray = { 'H', 'E', 'L', 'L', 'O' };

System.out.println( "Array integerArray contains:" );

printArray( intArray ); // pass an Integer array

System.out.println( "\nArray doubleArray contains:" );

printArray( doubleArray ); // pass a Double array

System.out.println( "\nArray characterArray contains:" );

printArray( charArray ); // pass a Character array

This would produce the following result:

Array integerArray contains:

1 2 3 4 5 6

Array doubleArray contains:

1.1 2.2 3.3 4.4

Array characterArray contains:

H E L L O
Generics in Methods and Constructors
Sometimes we don’t want whole class to be parameterized, in that case we can use
generics type in methods also. Since constructor is a special kind of method, we can use
generics type in constructors too.

Here is a class showing example of generics type in method.

package com.journaldev.generics;

public class GenericsMethods {

//Generics in method

public static <T> boolean isEqual(GenericsType<T> g1, GenericsType<T> g2){

return g1.get().equals(g2.get());

public static void main(String args[]){

GenericsType<String> g1 = new GenericsType<>();

g1.set("Pankaj");
GenericsType<String> g2 = new GenericsType<>();

g2.set("Pankaj");

boolean isEqual = GenericsMethods.<String>isEqual(g1, g2);

//above statement can be written simply as

isEqual = GenericsMethods.isEqual(g1, g2);

//This feature, known as type inference, allows you to invoke a generic

method as an ordinary method, without specifying a type between angle brackets.

//Compiler will infer the type that is needed

Notice the isEqual method signature showing syntax to use generics type in methods. Also
notice how to use these methods in our java program. We can specify type while calling
these methods or we can invoke them like a normal method. Java compiler is smart enough
to determine the type of variable to be used, this facility is called as type inference.

Implementing TCP/IP based Server and Client


TCPClient.java:
import java.io.*;
import java.net.*;

class TCPClient {
public static void main(String args[]) throws Exception {
String sentence;
String modifiedSentence;
BufferedReader inFromUser = new BufferedReader(new
InputStreamReader(System.in));
Socket clientSocket = new Socket("127.0.0.1", 6789);
DataOutputStream outToServer = new
DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + "\n");
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER:" + modifiedSentence);
clientSocket.close();
}
}
TCPServer.java:
import java.io.*;
import java.net.*;

class TCPServer {
public static void main(String args[]) throws Exception {
int firsttime = 1;
while (true) {
String clientSentence;
String capitalizedSentence="";
ServerSocket welcomeSocket = new ServerSocket(3248);
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(new
InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new
DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
//System.out.println(clientSentence);
if (clientSentence.equals("set")) {
outToClient.writeBytes("connection is ");
System.out.println("running here");
//welcomeSocket.close();
//outToClient.writeBytes(capitalizedSentence);
}
capitalizedSentence = clientSentence.toUpperCase() + "\n";
//if(!clientSentence.equals("quit"))
outToClient.writeBytes(capitalizedSentence+"enter the message or command:
");
System.out.println("passed");
//outToClient.writeBytes("enter the message or command: ");
welcomeSocket.close();
System.out.println("connection terminated");
}
}
}
SwingControlDemo.java
package com.tutorialspoint.gui;

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class SwingControlDemo {

private JFrame mainFrame;

private JLabel headerLabel;

private JLabel statusLabel;

private JPanel controlPanel;

public SwingControlDemo(){

prepareGUI();

public static void main(String[] args){

SwingControlDemo swingControlDemo = new SwingControlDemo();

swingControlDemo.showEventDemo();

private void prepareGUI(){

mainFrame = new JFrame("Java SWING Examples");

mainFrame.setSize(400,400);

mainFrame.setLayout(new GridLayout(3, 1));

headerLabel = new JLabel("",JLabel.CENTER );

statusLabel = new JLabel("",JLabel.CENTER);

statusLabel.setSize(350,100);
mainFrame.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent windowEvent){

System.exit(0);

});

controlPanel = new JPanel();

controlPanel.setLayout(new FlowLayout());

mainFrame.add(headerLabel);

mainFrame.add(controlPanel);

mainFrame.add(statusLabel);

mainFrame.setVisible(true);

private void showEventDemo(){

headerLabel.setText("Control in action: Button");

JButton okButton = new JButton("OK");

JButton submitButton = new JButton("Submit");

JButton cancelButton = new JButton("Cancel");

okButton.setActionCommand("OK");

submitButton.setActionCommand("Submit");

cancelButton.setActionCommand("Cancel");

okButton.addActionListener(new ButtonClickListener());

submitButton.addActionListener(new ButtonClickListener());

cancelButton.addActionListener(new ButtonClickListener());

controlPanel.add(okButton);

controlPanel.add(submitButton);

controlPanel.add(cancelButton);
mainFrame.setVisible(true);

private class ButtonClickListener implements ActionListener{

public void actionPerformed(ActionEvent e) {

String command = e.getActionCommand();

if( command.equals( "OK" )) {

statusLabel.setText("Ok Button clicked.");

else if( command.equals( "Submit" ) ) {

statusLabel.setText("Submit Button clicked.");

else {

statusLabel.setText("Cancel Button clicked.");

Вам также может понравиться