Академический Документы
Профессиональный Документы
Культура Документы
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(){
}
If we compile and run the above program, then it would produce the following result:
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
import java.applet.*;
import java.awt.*;
Now compile the above code and call the generated class in your HTML code as follows:
<HTML>
<HEAD>
</HEAD>
<BODY>
<div >
</APPLET>
</div>
</BODY>
</HTML>
Result:
The above code sample will produce the following result in a java enabled web browser.
Event Handling
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import java.applet.Applet;
import java.awt.Graphics;
implements MouseListener {
StringBuffer strBuffer;
addMouseListener(this);
System.out.println(word);
strBuffer.append(word);
repaint();
g.drawRect(0, 0,
getWidth() - 1,
getHeight() - 1);
<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());
}
}
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());
}
}
MULTITHREADING
class RunnableDemo implements Runnable {
private Thread t;
threadName = name;
try {
Thread.sleep(50);
} catch (InterruptedException e) {
if (t == null)
t.start ();
R1.start();
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
class PrintDemo {
try {
} catch (Exception e) {
System.out.println("Thread interrupted.");
private Thread t;
PrintDemo PD;
threadName = name;
PD = pd;
synchronized(PD) {
PD.printCount();
if (t == null)
t.start ();
T1.start();
T2.start();
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
Counter --- 5
Counter --- 4
Counter --- 3
Counter --- 2
Counter --- 1
Byte/Character Stream
import java.io.*;
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.*;
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;
InputStream is = null;
InputStreamReader isr = null;
BufferedReader br = null;
try{
// open input stream test.txt for reading purpose.
is = new FileInputStream("c:/test.txt");
// prints character
System.out.println(c);
}
}catch(Exception e){
e.printStackTrace();
}finally{
Buffered Writer
package com.tutorialspoint;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.StringWriter;
StringWriter sw = null;
BufferedWriter bw = null;
try{
// create string writer
sw = new StringWriter();
}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 AWTGraphicsDemo(){
prepareGUI();
awtGraphicsDemo.setVisible(true);
setSize(400,400);
addWindowListener(new WindowAdapter() {
System.exit(0);
});
@Override
g.setColor(Color.GRAY);
g.setFont(font);
Panel Example
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
mainFrame.setVisible(true);
}
}
Frame Example
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
public AwtContainerDemo(){
prepareGUI();
awtContainerDemo.showFrameDemo();
mainFrame.setSize(400,400);
mainFrame.addWindowListener(new WindowAdapter() {
});
headerLabel.setAlignment(Label.CENTER);
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);
msglabel.setAlignment(Label.CENTER);
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
frame.setSize(300, 300);
frame.setLayout(new FlowLayout());
frame.add(msglabel);
frame.addWindowListener(new WindowAdapter() {
frame.dispose();
});
okButton.addActionListener(new ActionListener() {
frame.setVisible(true);
});
controlPanel.add(okButton);
mainFrame.setVisible(true);
// Create buttons
b1=new Button(); // Create a button with
default constructor
b1.setLabel("I am button 1"); // Set the
text for button
}
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;
// Create a frame
Frame frame = new Frame("Example Frame");
/*
*/
Panel panel = new Panel();
frame.setVisible(true);
}
}
Creating JDBC Application
import java.sql.*;
// Database credentials
try{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
int id = rs.getInt("id");
//Display values
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end try
System.out.println("Goodbye!");
}//end main
}//end FirstExample
Code that uses generics has many benefits over non-generic code:
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:
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:
private T t;
this.t = t;
public T get() {
return t;
integerBox.add(new Integer(10));
}
}
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:
System.out.println();
Integer[] intArray = { 1, 2, 3, 4, 5 };
1 2 3 4 5 6
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.
package com.journaldev.generics;
//Generics in method
return g1.get().equals(g2.get());
g1.set("Pankaj");
GenericsType<String> g2 = new GenericsType<>();
g2.set("Pankaj");
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.
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 SwingControlDemo(){
prepareGUI();
swingControlDemo.showEventDemo();
mainFrame.setSize(400,400);
statusLabel.setSize(350,100);
mainFrame.addWindowListener(new WindowAdapter() {
System.exit(0);
});
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
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);
else {